Skip to content

Instantly share code, notes, and snippets.

@larsaugustin
Created August 19, 2020 16:59
Show Gist options
  • Save larsaugustin/a61873eec70ac35367c54d5ee5dd3d61 to your computer and use it in GitHub Desktop.
Save larsaugustin/a61873eec70ac35367c54d5ee5dd3d61 to your computer and use it in GitHub Desktop.
Conditional view modifiers in SwiftUI
struct ExampleView: View {
var body: some View {
Text("Example")
.if(true) { $0.foregroundColor(.red) }
}
}
extension View {
@ViewBuilder
public func `if`<V>(_ condition: Bool, input: (Self) -> V) -> some View where V: View {
if condition {
input(self)
} else {
self
}
}
}
@rolandleth
Copy link

For those times you need an else as well:

@ViewBuilder
func `if`<T: View, O: View>(_ condition: Bool, transform: @escaping (Self) -> T, else: @escaping (Self) -> O) -> some View {
	if condition {
		transform(self)
	} else {
		`else`(self)
	}
}
struct ExampleView: View {
    var body: some View {
        Text("Example")
            .if(true) { 
                $0.foregroundColor(.red) 
            } else: { 
                $0.foregroundColor(.blue) 
            }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment