📦ViewBuilder
From Xcode 12, both switch and if let are supported in the ViewBuilder!
ViewBuilder as a Parameter
SwiftUI ⟩ ViewBuilder
Using ViewBuilder ⭐️
共有四個步驟:
// ⭐️ Step 1: Create a View struct like this:
// ⭐️ Note : `Content` conforms to `View`
struct MyContainerView<Content: View>: View {
...
}// ⭐️ Step 2: Add `content` property and initializer
struct MyContainerView<Content: View>: View {
let content: Content
init(@ViewBuilder content: () -> Content) {
self.content = content()
}
}// ⭐️ Step 3: Implementing `View` protocol requirement
struct MyContainerView<Content: View>: View {
let content: Content
var body: some View {
// use `content` somewhere in your code
content
// ... (other customizations)
}
}Examples
在 📦 Card 中:
content 是一個擁有 @ViewBuilder 屬性的 closure, 因此我們在使用 Card 的時候,可以像用 HStack 一樣, 使用下面的語法:
其中 { ... } 就是 content closure。
但這個 closure 並不是一般的 closure,它是一個 ViewBuilder, 意思就是說:這個 closure 裡面「每一行程式碼」所產生的 view都會變成 ViewBuilder 裡面的某個 buildBlock() 的「參數」,例如我們輸入:
這段程式碼其實會呼叫 ViewBuilder 的: .buildBlock(C0, C1) 函數,然後產生一個新的 view 出來,而這個 view 的型別就會被自動設定成 Content。以上面的例子來說,

View Builders - NetSplit.com
Last updated
Was this helpful?