📦ViewBuilder
From Xcode 12, both switch and if let are supported in the ViewBuilder!
ViewBuilder as a Parameter
Using ViewBuilder ⭐️
共有四個步驟:
// ⭐️ Step 1: Create a View struct like this:
// ⭐️ Note : `Content` conforms to `View`
struct MyContainerView<Content: View>: View {
...
}
Examples
// ⭐️ generic structure
struct Card<Content> : View where Content : View {
// ⭐️ 卡片的內容,由 .init(content:) 傳進來。
// ⭐️ `Content` 的型別也是由 init(content:) 決定。
var content: Content
// init(content:)
init(@ViewBuilder content: () -> Content) { // ⭐️ @ViewBuilder
self.content = content()
}
// view body
var body: some View {
// 卡片內容
content
// 卡片風格
.padding() // 留白邊
.foregroundColor(.black)
.background(Color.white) // 白背景
.cornerRadius(8) // 截圓角
.shadow(radius: 4) // 畫陰影
}
}
Last updated
Was this helpful?