Last active
May 30, 2024 17:56
-
-
Save kovs705/24faa43e83e20ad45408509773cbb7c5 to your computer and use it in GitHub Desktop.
`If` condition for views in SwiftUI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
}) | |
*/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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