How to reuse views using @ViewBuilder - SwiftUI
The body
property of any SwiftUI automatically gets the ability to return different views thanks to a special attributed called @ViewBuilder
. This is implemented using Swift’s result builder system, and it understands how to present two different views depending on our app’s state. Examples:
Reusable view without arguments
struct ContentView: View {
@ViewBuilder var tossResult: some View {
if Bool.random() {
Image("laser-show")
.resizable()
.scaledToFit()
} else {
Text("Better luck next time")
.font(.title)
}
}
var body: some View {
VStack {
Text("Coin Flip")
.font(.largeTitle)
tossResult
.frame(width: 400, height: 300)
}
}
}
Reusable view with arguments
Here we are taking a String
from another view and using it here.
Usage on other views: CoinRowView(for: "Title")
@ViewBuilder
func CoinRowView(for coin: String) -> some View {
ZStack {
Text(coin)
}
}