SwiftUI 檢視重構
來源:取自 @Dimillian 的 Dimillian/Skills (2025-12-31)。
概述
為 SwiftUI 檢視套用一致的結構與依賴模式,重點關注排序、Model-View (MV) 模式、謹慎的檢視模型處理,以及正確的 Observation 使用方式。
核心指導方針
1) 檢視屬性排序(由上至下)
- Environment
private/publiclet@State/ 其他儲存屬性- computed
var(非檢視) initbody- computed 檢視建構器 / 其他檢視輔助屬性
- 輔助 / 非同步函數
2) 偏好 MV (Model-View) 模式
- 預設使用 MV:檢視是輕量的狀態表達式;模型/服務擁有商業邏輯。
- 優先使用
@State、@Environment、@Query以及task/onChange進行協調。 - 透過
@Environment注入服務與共享模型;保持檢視小巧且可組合。 - 將大型檢視拆分成子檢視,而非引入檢視模型。
3) 拆分大型 body 與檢視屬性
- 若
body超出一個畫面或包含多個邏輯區塊,請將其拆分成較小的子檢視。 - 當大型 computed 檢視屬性(如
var header: some View { ... })攜帶狀態或複雜分支時,將其提取為專用的View型別。 - 可以將相關的子檢視作為 computed 檢視屬性保留在同一個檔案中;只有在結構上合理或預期要重複使用時,才將其提取為獨立的
View結構。 - 偏好傳遞小型的輸入資料(資料、綁定、回呼),而非重複使用整個父檢視的狀態。
範例(提取區塊):
var body: some View {
VStack(alignment: .leading, spacing: 16) {
HeaderSection(title: title, isPinned: isPinned)
DetailsSection(details: details)
ActionsSection(onSave: onSave, onCancel: onCancel)
}
}
範例(長 body → 較短的 body + 同檔案中的 computed 檢視):
var body: some View {
List {
header
filters
results
footer
}
}
private var header: some View {
VStack(alignment: .leading, spacing: 6) {
Text(title).font(.title2)
Text(subtitle).font(.subheadline)
}
}
private var filters: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack {
ForEach(filterOptions, id: \.self) { option in
FilterChip(option: option, isSelected: option == selectedFilter)
.onTapGesture { selectedFilter = option }
}
}
}
}
範例(提取複雜的 computed 檢視):
private var header: some View {
HeaderSection(title: title, subtitle: subtitle, status: status)
}
private struct HeaderSection: View {
let title: String
let subtitle: String?
let status: Status
var body: some View {
VStack(alignment: .leading, spacing: 4) {
Text(title).font(.headline)
if let subtitle { Text(subtitle).font(.subheadline) }
StatusBadge(status: status)
}
}
}
4) 檢視模型處理(僅在已存在時)
- 除非需求或現有程式碼明確要求,否則請勿引入檢視模型。
- 如果檢視模型已存在,請儘可能使其非可選。
- 透過
init將依賴傳遞給檢視,然後在檢視的init中將它們傳遞給檢視模型。 - 避免使用
bootstrapIfNeeded模式。
範例(基於 Observation):
@State private var viewModel: SomeViewModel
init(dependency: Dependency) {
_viewModel = State(initialValue: SomeViewModel(dependency: dependency))
}
5) Observation 使用方式
- 對於
@Observable參考型別,請將其作為@State儲存在根檢視中。 - 根據需要顯式向下傳遞可觀察物件;除非必要,否則避免使用可選狀態。
工作流程
- 重新排序檢視以符合排序規則。
- 偏好 MV:使用
@State、@Environment、@Query、task與onChange將輕量協調邏輯移入檢視。 - 如果存在檢視模型,請將可選檢視模型替換為在
init中透過從檢視傳遞依賴而初始化的非可選@State檢視模型。 - 確認 Observation 使用方式:根
@Observable檢視模型使用@State,無冗餘包裝器。 - 保持行為不變:除非要求,否則不要更改佈局或商業邏輯。
注意事項
- 偏好小型顯式輔助屬性,而非大型條件區塊。
- 將 computed 檢視建構器保持在
body下方,非檢視的 computed var 保持在init上方。 - 關於 MV 優先指導與原理,請參閱
references/mv-patterns.md。