swift_swiftui

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

SwiftUI

SwiftUI

This skill covers SwiftUI framework concepts for building declarative user interfaces.
本技能涵盖了用于构建声明式用户界面的SwiftUI框架相关概念。

Overview

概述

SwiftUI is Apple's modern declarative framework for building user interfaces across all Apple platforms using a reactive, state-driven approach.
SwiftUI是苹果推出的现代声明式框架,采用响应式、状态驱动的方法,可在所有苹果平台上构建用户界面。

Available References

可用参考资料

  • Property Wrappers - @State, @Binding, @ObservedObject, @StateObject, @Environment
  • 属性包装器 - @State、@Binding、@ObservedObject、@StateObject、@Environment

Quick Reference

快速参考

State Management Decision Tree

状态管理决策树

Need local mutable state?
├── YES → Is it a value type?
│   ├── YES → Use @State
│   └── NO → Use @StateObject
└── NO → Shared from parent?
    ├── YES → Is it value type?
    │   ├── YES → Use @Binding
    │   └── NO → Use @ObservedObject
    └── NO → Use @Environment
是否需要本地可变状态?
├── 是 → 它是值类型吗?
│   ├── 是 → 使用@State
│   └── 否 → 使用@StateObject
└── 否 → 从父视图共享?
    ├── 是 → 它是值类型吗?
    │   ├── 是 → 使用@Binding
    │   └── 否 → 使用@ObservedObject
    └── 否 → 使用@Environment

Property Wrappers

属性包装器

WrapperOwns DataData TypeUse For
@StateYesValue typeLocal UI state
@BindingNoValue typeShared state with parent
@ObservedObjectNoReference typeInjected dependencies
@StateObjectYesReference typeOwned view models
@EnvironmentNoAnyShared resources
包装器是否拥有数据数据类型适用场景
@State值类型本地UI状态
@Binding值类型与父视图共享状态
@ObservedObject引用类型注入依赖项
@StateObject引用类型自有视图模型
@Environment任意类型共享资源

Common Usage Patterns

常见使用模式

swift
// Local state
struct CounterView: View {
    @State private var count = 0
    
    var body: some View {
        Button("Count: \(count)") { count += 1 }
    }
}

// Shared state (parent to child)
struct ParentView: View {
    @State private var isOn = false
    
    var body: some View {
        ChildView(isOn: $isOn)
    }
}

struct ChildView: View {
    @Binding var isOn: Bool
    
    var body: some View {
        Toggle("Enable", isOn: $isOn)
    }
}

// Observable object
class ViewModel: ObservableObject {
    @Published var items: [Item] = []
}

struct ContentView: View {
    @StateObject private var viewModel = ViewModel()
    
    var body: some View {
        List(viewModel.items) { item in
            Text(item.name)
        }
    }
}

// Environment values
struct EnvironmentView: View {
    @Environment(\.colorScheme) var colorScheme
    @Environment(\.dismiss) var dismiss
    
    var body: some View {
        Text(colorScheme == .dark ? "Dark" : "Light")
    }
}
swift
// 本地状态
struct CounterView: View {
    @State private var count = 0
    
    var body: some View {
        Button("Count: \(count)") { count += 1 }
    }
}

// 共享状态(父视图到子视图)
struct ParentView: View {
    @State private var isOn = false
    
    var body: some View {
        ChildView(isOn: $isOn)
    }
}

struct ChildView: View {
    @Binding var isOn: Bool
    
    var body: some View {
        Toggle("Enable", isOn: $isOn)
    }
}

// 可观察对象
class ViewModel: ObservableObject {
    @Published var items: [Item] = []
}

struct ContentView: View {
    @StateObject private var viewModel = ViewModel()
    
    var body: some View {
        List(viewModel.items) { item in
            Text(item.name)
        }
    }
}

// 环境值
struct EnvironmentView: View {
    @Environment(\.colorScheme) var colorScheme
    @Environment(\.dismiss) var dismiss
    
    var body: some View {
        Text(colorScheme == .dark ? "Dark" : "Light")
    }
}

Best Practices

最佳实践

  1. Use @State for local UI state - Toggles, text fields, counters
  2. Lift state up when shared - Single source of truth
  3. Use @StateObject for owned view models - Survives view recreation
  4. Pass @Binding to child views - Two-way data flow
  5. Keep @State minimal - Only store what's needed for UI
  6. Use @Environment for system values - Color scheme, locale, etc.
  7. Access on main thread - All property wrappers require @MainActor
  8. Initialize with underscore -
    _count = State(initialValue:)
  1. 使用@State管理本地UI状态 - 开关、文本框、计数器
  2. 共享状态时提升状态层级 - 单一数据源
  3. 使用@StateObject管理自有视图模型 - 可在视图重建时保留
  4. 向子视图传递@Binding - 双向数据流
  5. 尽量精简@State的使用 - 仅存储UI所需的数据
  6. 使用@Environment获取系统值 - 配色方案、区域设置等
  7. 在主线程访问 - 所有属性包装器都需要@MainActor
  8. 使用下划线初始化 -
    _count = State(initialValue:)

Common Pitfalls

常见陷阱

PitfallSolution
Initializing @State directlyUse
_property = State(initialValue:)
Creating @ObservedObject in initUse @StateObject instead
Mutating on background threadDispatch to main queue
Passing @State instead of BindingUse
$property
for Binding
常见问题解决方案
直接初始化@State使用
_property = State(initialValue:)
在init中创建@ObservedObject改用@StateObject
在后台线程修改状态调度到主队列
传递@State而非Binding使用
$property
获取Binding

For More Information

更多信息

Visit https://swiftzilla.dev for comprehensive SwiftUI documentation.
如需了解更多信息,请访问https://swiftzilla.dev获取全面的SwiftUI文档。