๐Ÿ“ฆViewBuilder

SwiftUI โŸฉ Views โŸฉ

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?