History
Loading...
Loading...
September 16, 2025
@ViewBuilder functions to extract complex view logic while maintaining clean composition. Instead of cramming everything into your main view body, create focused, reusable subview functions that return specific UI components.Breaking complex views into focused subview functions creates cleaner, more maintainable code. Each `@ViewBuilder` function handles a specific UI responsibility, making the main body readable and the components reusable.
struct ProductDetailView: View {
let product: Product
@State private var isExpanded = false
var body: some View {
ScrollView {
VStack(spacing: 16) {
productHeader
productDetails
actionButtons
}
}
}
@ViewBuilder
private var productHeader: some View {
VStack(alignment: .leading, spacing: 8) {
AsyncImage(url: product.imageURL) { image in
image.resizable().aspectRatio(contentMode: .fit)
} placeholder: {
Rectangle().fill(.gray.opacity(0.3))
}
.frame(height: 200)
Text(product.name)
.font(.title2)
.fontWeight(.semibold)
}
}
@ViewBuilder
private var productDetails: some View {
VStack(alignment: .leading, spacing: 12) {
Text(product.description)
.lineLimit(isExpanded ? nil : 3)
.animation(.easeInOut(duration: 0.3), value: isExpanded)
Button(isExpanded ? "Show Less" : "Show More") {
isExpanded.toggle()
}
.foregroundColor(.blue)
}
}
@ViewBuilder
private var actionButtons: some View {
HStack(spacing: 16) {
Button("Add to Cart") { /* action */ }
.buttonStyle(.borderedProminent)
Button("Save for Later") { /* action */ }
.buttonStyle(.bordered)
}
}
}This approach improves code organization, enhances readability, simplifies testing individual components, and makes it easier to modify specific UI sections without affecting the entire view. It also enables better SwiftUI view diffing performance by creating clear component boundaries.