Reputation: 843
So say I want to conditionally enable or disable a modifier on a view such as matched geometry effect? As silly as this looks, how would I do this?
Image("Test")
.scaleEffect(self.selectedImageScale)
.offset(self.selectedImageOffset)
.aspectRatio(contentMode: .fit)
if disabled {
.matchedGeometryEffect(id: selectedImage.id, in: self.namespace)
}
Upvotes: 3
Views: 1069
Reputation: 119380
You can achieve it with a simple extension on the View
:
extension View {
@ViewBuilder
public func `if`<T: View, U: View>(
_ condition: Bool,
then modifierT: (Self) -> T,
else modifierU: (Self) -> U
) -> some View {
if condition { modifierT(self) }
else { modifierU(self) }
}
}
Now you can use it like:
Image("Test")
.scaleEffect(self.selectedImageScale)
.offset(self.selectedImageOffset)
.aspectRatio(contentMode: .fit)
.if(disabled) { view in
view.matchedGeometryEffect(id: selectedImage.id, in: self.namespace)
} else { $0 } // returns unmodified view
Upvotes: 3
Reputation: 12125
You can't put an if
around a modifier, but you can use a ternary statement inside the parameters of the modifier:
.matchedGeometryEffect(id: disabled ? 0 : selectedImage.id, in: self.namespace)
Not sure if 0 works here for a "disabled" id, depends on your ids.
Upvotes: 0