How to use ViewBuilder in SwiftUI
Issue #767
SwiftUI ‘s ViewBuilder is a custom parameter attribute that constructs views from closures.
It is available in body
and most SwiftUI modifiers
1 | public protocol View { |
In these ViewBuilder
enabled places we can perform conditional logic to construct views. For example here in our SampleView, we have switch
statement in body
1 | struct SampleView: View { |
ViewBuilder
applies to both property and function. If we want to have the same logic style as in body
in our custom property or methods, we can annotate with ViewBuilder
. This works like magic, SwiftUI can determine the types of our expression.
1 | extension SampleView { |
Use ViewBuilder to construct View
We can use ViewBuiler
as our parameter that constructs View. For example we can build an IfLet
that construct View with optional check.
1 | public struct IfLet<T, Content: View>: View { |
With ViewBuilder
we can apply logic inside our closure
1 | struct EmailView: View { |
Use ViewBuilder where we can’t use closure
In some modifers like overlay
, SwiftUI expects a View, not a closure that returns a View. There we cannot use additional logic
1 | extension View { |
The below won’t work as we can’t do conditional statement in overlay modifier
1 | struct MessageView: View { |
But we can make something like MakeView
that provides a ViewBuilder
closure
1 | public struct MakeView<Content: View>: View { |
So we can use a conditional statement in any modifier that does not accept ViewModifier
1 | struct MessageView: View { |