Using Conditional Modifiers in SwiftUI
Learn different ways to add a conditional modifier to your SwiftUI view
In your SwiftUI application, you might want add a modifier to an element depending on a certain condition.
There are multiple ways to achieve that: wrapping everything in an if else statement, adding a ternary operator in a modifier, or creating a View extension so that we can simply add a .if modifier.
In this section, we'll cover the three methods.
If else statement
- The first method is to wrap our entire content in an if else statement.
- This is good if you have little content, but it might become hard to read when your content becomes bigger. Also, the code is repeated two times, which is not good.
struct ContentView: View {
@State private var shouldBeRed: Bool = true
var body: some View {
if shouldBeRed {
Text("Hello, world!")
.foregroundColor(.red)
} else {
Text("Hello, world!")
.foregroundColor(.blue)
}
}
}
- Another way is to add a ternary operator inside of your modifier.
- This is a good method if the modifier should be applied even if the condition evaluates to false.
- It's easier to read, and is only a one-liner, which makes clean code.
struct ContentView: View {
@State private var shouldBeRed: Bool = true
var body: some View {
Text("Hello, world!")
.foregroundColor(shouldBeRed ? .red : .blue)
}
}
- However, if you only want to apply a modifier if a condition is true, the View extension is a good method.
- For example, you only want to add a shadow to your Text if the value of shouldAddShadow is true.
- If it's false, you don't want to add any shadow. Let's start by creating the View extension.
- This extension lets us add the .if modifier to our Views and will only apply the modifiers we add if the condition is met.
extension View {
@ViewBuilder func `if`<Content: View>(_ condition: Bool, transform: (Self) -> Content) -> some View {
if condition {
transform(self)
} else {
self
}
}
}
struct ContentView: View {
@State private var shouldAddShadow: Bool = true
var body: some View {
Text("Hello, world!")
.if(shouldAddShadow) { view in
view.shadow(color: .black, radius: 10, x: 0.0, y: 0.0)
}
}
}
Comments
Post a Comment