Conditional View Modifiers in SwiftUI

September 2, 2020 • 08:59 AM

Federico Zanetello:

The most common solution is to define a new if View extension:

extension View {
	@ViewBuilder
	func `if`<Transform: View>(
		_ condition: Bool,
		transform: (Self) -> Transform
	) -> some View {
		if condition {
			transform(self)
		} else {
			self
		}
	}
}

This function will apply transform to our view when condition is true, otherwise it will leave the original view untouched.

Going back to our example, this is one way to use it:

struct MyView: View {
	var body: some view {
		myView
			.if(X) { $0.padding(8) }
			.if(Y) { $0.background(Color.blue) }
	}
}

This is perfect.

Let’s stay in touch!

Sign up for weekly updates on this blog. No spams — I promise.

Blog Posts Archive