๐Ÿ“ฆViewBuilder

SwiftUI โŸฉ Views โŸฉ

From Xcode 12, both switch and if let are supported in the ViewBuilder!

You typically use ViewBuilder as a parameter attribute for child view-producing closure parameters, allowing those closures to provide multiple child views. ๐Ÿ‘‰ SwiftUI โŸฉ View โŸฉ ViewBuilder

As for ViewBuilders, it is mainly used to create custom container views, which can also become a reusable view component. ๐Ÿ‘‰ Understanding SwiftUI's ViewModifiers and ViewBuilders

A good rule of thumb for me has to be to use a modifier first, and only use a builder when the code patterns really pulled strongly for that syntax. ๐Ÿ‘‰ View Builders - NetSplit.com

@ViewBuilder is one of the possible function builders. ๐Ÿ‘‰ Swift with Majid

ViewBuilder as a Parameter

  • You typically use ViewBuilder as a parameter attribute for child view-producing closure parameters, allowing those closures to provide multiple child views.

  • ้€šๅธธ @ViewBuilder closure ๅ…ทๆœ‰ @escaping ็š„็‰นๆ€ง๏ผŒๅ› ็‚บไธ€่ˆฌ้€™ๅ€‹ closure ๆœƒๅœจ .init(content:) ไธญๅ‚ณ้€ฒไพ†๏ผŒ็„ถๅพŒๅœจ var body ไธญ็”จๅˆฐ๏ผŒๅฆ‚ๆžœๆฒ’ๆœ‰ไบ‹ๅ…ˆ่จญ็‚บ @escaping ็š„่ฉฑ๏ผŒ้‚ฃ้บผ้€™ๅ€‹ closure ๅœจ .init ไธญๅ‚ณ้€ฒไพ†ๅพŒ๏ผŒๆœƒ้šจ่‘— .init ็ตๆŸ่€Œๆถˆๅคฑ๏ผŒๅ› ๆญคไนŸๆฒ’่พฆๆณ•ไบ‹ๅพŒๅœจ var body ไธญ็”จๅˆฐ๏ผŒๆ‰€ไปฅๆœƒ็”ข็”Ÿ compiler ้Œฏ่ชคใ€‚ ๅ•๏ผš้‚ฃ้บผ @escaping closure ๆœƒๅญ˜ๆ”พๅœจ้‚ฃ่ฃๅ‘ข ๐Ÿค”โ“ ็ญ”๏ผš้€šๅธธๆœƒๅญ˜ๆ”พๅœจๅ‡ฝๆ•ธๅค–้ƒจ็š„่ฎŠๆ•ธๆˆ–้™ฃๅˆ—ไธญใ€‚

  • ไฝ†ๅ้Žไพ†่ชช๏ผŒๅฆ‚ๆžœๅ‚ณ้€ฒไพ†็š„ @ViewBuilder closure ้ฆฌไธŠๅœจ .init ไธญๅฐฑ็”จๆŽ‰ไบ†๏ผŒ้€™ๆ™‚ๅฐฑไธ้œ€่ฆๅŠ  @escaping ้€™ๅ€‹ๅฑฌๆ€งไบ†ใ€‚

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