Skip to content

Instantly share code, notes, and snippets.

@kovs705
Last active May 30, 2024 17:56
Show Gist options
  • Save kovs705/24faa43e83e20ad45408509773cbb7c5 to your computer and use it in GitHub Desktop.
Save kovs705/24faa43e83e20ad45408509773cbb7c5 to your computer and use it in GitHub Desktop.
`If` condition for views in SwiftUI
extension View {
@ViewBuilder
func applyIfTrue<Content: View>(_ condition: @autoclosure () -> Bool,
ifTrue applyTrue: (Self) -> Content) -> some View {
if condition() {
applyTrue(self)
} else {
self
}
}
/// Conditionally applies a modification to the view.
///
/// - Parameters:
/// - condition: The condition that determines which modification to apply.
/// - applyTrue: A closure that modifies the view if the condition is `true`.
/// - applyFalse: A closure that modifies the view if the condition is `false`.
/// - Returns: A view modified according to the condition.
@ViewBuilder func applyIf<TrueContent: View, FalseContent: View>(_ condition: @autoclosure () -> Bool, ifTrue applyTrue: (Self) -> TrueContent, ifFalse applyFalse: (Self) -> FalseContent) -> some View {
if condition() {
applyTrue(self)
} else {
applyFalse(self)
}
}
}
// MARK: - Usage
/*
Text("Hi")
.applyIfTrue(`condition`, ifTrue: { view in
view.ignoresSafeArea(.container)
})
*/
extension View {
@ViewBuilder func `if`<Content: View>(_ condition: Bool, transform: (Self) -> Content) -> some View {
if condition {
transform(self)
} else {
self
}
}
}
// MARK: - Usage
/*
Text("Hi")
.if(`condition`) { view in
view
.background(Color.red)
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment