Refactor SwiftUI View
Extract and refactor SwiftUI views for better maintainability.
When to Refactor
- View exceeds 100 lines
- Deeply nested view hierarchy
- Repeated view patterns
- Complex conditional logic in body
- Performance issues from large views
Workflow
1. Analyze Current View
- Read the source file
- Identify logical sections
- Find repeated patterns
- Note dependencies and state
2. Plan Extraction
Extract Subviews For:
- Distinct UI sections (header, content, footer)
- Repeated patterns (list rows, cards)
- Complex conditional views
- Reusable components
Keep Together:
- Tightly coupled logic
- Shared state that's complex to pass
- Animation coordination
3. Refactoring Patterns
Extract as Computed Property
// Before
var body: some View {
VStack {
// 50 lines of header code
// 50 lines of content code
}
}
// After
var body: some View {
VStack {
headerView
contentView
}
}
@ViewBuilder
private var headerView: some View {
// Header code
}
@ViewBuilder
private var contentView: some View {
// Content code
}
Extract as Separate Struct
// For reusable components
struct ItemRow: View {
let item: Item
var body: some View {
HStack {
// Row content
}
}
}
Extract View Modifier
// Before: repeated styling
Text("Title")
.font(.headline)
.foregroundStyle(.primary)
.padding()
// After: custom modifier
Text("Title")
.titleStyle()
extension View {
func titleStyle() -> some View {
self
.font(.headline)
.foregroundStyle(.primary)
.padding()
}
}
4. Verify Refactoring
- Build succeeds
- Previews work
- Behavior unchanged
- Tests still pass
Best Practices
- Pass only needed data to subviews
- Use @Binding for two-way data flow
- Prefer composition over deep nesting
- Keep related views in same file initially
- Extract to separate files when reused
- Add previews for extracted components