SwiftUI 中的 Form 视图使得创建表单变得简单易行。以下是基本的表单设计步骤:
- 在主视图 Body 中创建 Form 视图
struct ContentView: View {
var body: some View {
NavigationView {
Form {
// 表单内容
}
.navigationBarTitle("My Form")
}
}
}
- 添加 Section
struct ContentView: View {
var body: some View {
NavigationView {
Form {
Section(header: Text("Personal Information")) {
// Personal Information 表单内容
}
Section(header: Text("Preferences")) {
// Preferences 表单内容
}
}
.navigationBarTitle("My Form")
}
}
}
- 添加表单元素
TextField("Name", text: $name)
Toggle(isOn: $isOn) {
Text("Label")
}
DatePicker(selection: $date, displayedComponents: .date) {
Text("Date")
}
完整示例:
struct ContentView: View {
@State private var name = ""
@State private var isOn = false
@State private var date = Date()
var body: some View {
NavigationView {
Form {
Section(header: Text("Personal Information")) {
TextField("Name", text: $name)
DatePicker(selection: $date, displayedComponents: .date) {
Text("Date of Birth")
}
}
Section(header: Text("Preferences")) {
Toggle(isOn: $isOn) {
Text("Receive Notifications")
}
}
}
.navigationBarTitle("My Form")
}
}
}