Here's an answer similar to what Kiran Jasvanee posted, but simplified:
struct ContentView: View {
var body: some View {
Text("Hello, World!")
.modifier(ConditionalModifier(isBold: true))
}
}
struct ConditionalModifier: ViewModifier {
var isBold: Bool
func body(content: Content) -> some View {
Group {
if self.isBold {
content.font(.custom("HelveticaNeue-Bold", size: 14))
}
else{
content.font(.custom("HelveticaNeue", size: 14))
}
}
}
}
The difference is that there's no need to add this extension:
extension View {
func conditionalView(_ value: Bool) -> some View {
self.modifier(ConditionalModifier(isBold: value))
}
}
In the ConditionalModifier
struct, you could also eliminate the Group view and instead use the @ViewBuilder
decorator, like so:
struct ConditionalModifier: ViewModifier {
var isBold: Bool
@ViewBuilder
func body(content: Content) -> some View {
// Group {
if self.isBold {
content.font(.custom("HelveticaNeue-Bold", size: 14))
}
else{
content.font(.custom("HelveticaNeue", size: 14))
}
// }
}
}
You must either use a Group view (or some other parent view) or the @ViewBuilder
decorator if you want to conditionally display views.
Here's another example in which the the text of a button can be toggled between bold and not bold:
struct ContentView: View {
@State private var makeBold = false
var body: some View {
Button(action: {
self.makeBold.toggle()
}, label: {
Text("Tap me to Toggle Bold")
.modifier(ConditionalModifier(isBold: makeBold))
})
}
}
struct ConditionalModifier: ViewModifier {
var isBold: Bool
func body(content: Content) -> some View {
Group {
if self.isBold {
content.font(.custom("HelveticaNeue-Bold", size: 14))
}
else{
content.font(.custom("HelveticaNeue", size: 14))
}
}
}
}