swiftswiftui

SwiftUI Container Views: Smart Content Organization with ViewBuilder Magic

Daily tips and best practices

Tip
Use @ViewBuilder functions to create reusable container components that accept multiple child views. Instead of passing single views, you can build flexible containers like CardContainer { Text('Title'); Text('Subtitle') } that automatically handle layout and styling for any content you pass in.
Best Practice: Create Type-Safe Container Views with Generic Content

This pattern creates reusable container components that accept any SwiftUI content through ViewBuilder closures. The container handles consistent styling, spacing, and visual treatment while remaining completely flexible about the content it displays.

struct CardContainer<Content: View>: View {
    let content: Content
    let title: String?
    
    init(title: String? = nil, @ViewBuilder content: () -> Content) {
        self.title = title
        self.content = content()
    }
    
    var body: some View {
        VStack(alignment: .leading, spacing: 12) {
            if let title {
                Text(title)
                    .font(.headline)
                    .foregroundStyle(.primary)
            }
            
            content
        }
        .padding()
        .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 12))
        .shadow(radius: 2, y: 1)
    }
}

// Usage
CardContainer(title: "User Profile") {
    HStack {
        AsyncImage(url: user.avatarURL)
            .frame(width: 50, height: 50)
        VStack(alignment: .leading) {
            Text(user.name)
            Text(user.email)
                .foregroundStyle(.secondary)
        }
    }
}

Why This is a Best Practice

Generic container views with ViewBuilder promote code reuse and maintain design consistency across your app. They separate layout concerns from content, making your UI more maintainable and allowing designers to update styling in one place while developers focus on content logic.

History

Loading...