Categories
ios swift swiftui

How do you create a SwiftUI view that takes an optional secondary View argument?

I am trying to create a custom SwiftUI view that acts like the default views where I can add extra content to a view with a method or optional initializer argument.

SomeCustomView(title: "string argument") {
// some view
}
SomeCustomView(title: "hello") {
// some view
}.sideContent {
// another view
}
// This style is acceptable too
SomeCustomView(title: "hello", sideContent: { /* another view */ }) {
// some view
}

How can I modify this view struct to behave like the above example?

struct SomeCustomView<Content>: View where Content: View {
let title: String
let content: Content
init(title: String, @ViewBuilder content: () -> Content) {
self.title = title
self.content = content()
}
var body: some View {
VStack {
Text(title)
content
}
}
}

Ideally I’d have two different body “templates” that I could switch between depending on if the sideContent method was called or sideContent parameter was set. For example,

var body: some View {
VStack {
Text(title)
content
}
}
// or
var otherBody: some View {
HStack {
VStack {
Text(title)
content
}
sideContent
}
}