Skip to content

Instantly share code, notes, and snippets.

@shaps80
Last active December 10, 2020 09:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shaps80/f61c0745843cf41cb7498a650c8ba54b to your computer and use it in GitHub Desktop.
Save shaps80/f61c0745843cf41cb7498a650c8ba54b to your computer and use it in GitHub Desktop.
extension View {
/// Conditionally apply modifiers to a view.
func `if`<Content: View>(_ condition: () -> Bool, content: (Self) -> Content) -> some View {
condition() ?
ViewBuilder.buildEither(first: content(self)) :
ViewBuilder.buildEither(second: self)
}
func `if`<Content: View>(_ condition: @autoclosure () -> Bool, content: (Self) -> Content) -> some View {
condition() ?
ViewBuilder.buildEither(first: content(self)) :
ViewBuilder.buildEither(second: self)
}
}
@shaps80
Copy link
Author

shaps80 commented Dec 9, 2020

Example:

Text("Hello world")
    .if(isHighlighted) { section in
         section.foregroundColor(.red)
    }

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