Form 在 SwiftUI 中的应用
在 SwiftUI 中,Form 是一个容器视图,用于创建表单样式的用户界面,特别适合数据输入、设置页面或任何需要分组和结构化布局的场景。
基本用法
import SwiftUI
struct ContentView: View {
@State private var name = ""
@State private var isOn = false
@State private var selectedOption = 0
var body: some View {
Form {
Section {
TextField("姓名", text: $name)
Toggle("启用", isOn: $isOn)
}
Section(header: Text("选项")) {
Picker("选择", selection: $selectedOption) {
Text("选项1").tag(0)
Text("选项2").tag(1)
}
.pickerStyle(SegmentedPickerStyle())
}
Section {
Button("提交") {
print("提交表单")
}
}
}
}
}
Form 的主要特点
- 自动样式:Form 会自动为包含的控件应用适合表单的样式
- 分组显示:通常与
Section结合使用,提供逻辑分组 - 平台适配:在不同平台上自动调整外观(iOS、macOS 等)
常见表单控件
可以在 Form 中使用各种 SwiftUI 控件:
Form {
// 文本输入
TextField("用户名", text: $username)
SecureField("密码", text: $password)
// 开关
Toggle("记住我", isOn: $rememberMe)
// 选择器
Picker("年龄", selection: $age) {
ForEach(0..<120) { number in
Text("\(number)")
}
}
// 日期选择
DatePicker("生日", selection: $birthday, displayedComponents: .date)
// 按钮
Button("登录") {
login()
}
// 链接
Link("隐私政策", destination: URL(string: "https://example.com/privacy")!)
}
高级用法
动态表单
struct DynamicFormView: View {
@State private var items = ["Item 1", "Item 2"]
var body: some View {
Form {
ForEach(items.indices, id: \.self) { index in
TextField("Item \(index + 1)", text: $items[index])
}
Button("Add Item") {
items.append("Item \(items.count + 1)")
}
}
}
}
表单样式定制
Form {
// 表单内容
}
.listStyle(GroupedListStyle()) // 设置列表样式
.environment(\.horizontalSizeClass, .regular) // 环境变量
表单验证
struct SignUpForm: View {
@State private var email = ""
@State private var password = ""
@State private var passwordConfirm = ""
private var passwordsMatch: Bool {
password == passwordConfirm && !password.isEmpty
}
var body: some View {
Form {
Section {
TextField("Email", text: $email)
.keyboardType(.emailAddress)
.autocapitalization(.none)
SecureField("Password", text: $password)
SecureField("Confirm Password", text: $passwordConfirm)
.foregroundColor(passwordsMatch ? .primary : .red)
}
Section {
Button("Sign Up") {
// 处理注册
}
.disabled(!passwordsMatch)
}
}
}
}
平台差异
- iOS/iPadOS:Form 呈现为分组表格样式,通常带有圆角
- macOS:Form 呈现为垂直排列的控件组,带有适当的间距
- watchOS:Form 有更适合小屏幕的紧凑布局
Form 是 SwiftUI 中构建数据输入界面的强大工具,它简化了创建美观、一致的表单界面的过程,同时自动适应不同平台的设计语言。