SwiftUI - 将表单分割成多个章节



SwiftUI 允许我们将表单的行划分成多个章节。章节用于将表单内容组织成有意义的组。每个章节都有一个可选的页眉和页脚,允许我们为表单的不同组提供标签。在 SwiftUI 中,我们可以借助 Section 视图来实现章节。它通常用于以结构化的方式组织数据,从而改善用户体验。

在 SwiftUI 中创建章节表单

我们可以借助 Section 视图在表单中创建章节。它创建相关内容的组,使表单更容易导航。它为分组内容提供页眉和页脚,以便用户可以了解更多关于分组内容的信息。单个表单可以包含多个章节。

语法

以下是语法:

Form{
   Section(){
      content
   }header:{
      //content
   }
   Section{

   }footer:{

   }
}

示例 1

以下 SwiftUI 程序创建一个包含一个章节的简单表单。

import SwiftUI

struct ContentView: View {
   @State private var name: String = ""
   @State private var email: String = ""
   @State private var about: String = "Write about yourself..."
   @State private var notification = false
   @State private var city: String = "Delhi"

   var body: some View {
      NavigationStack{
         Form{
            Section{
               TextField("Enter Name", text: $name)
               TextField("Enter Email", text: $email)
               TextEditor(text: $about)
               Picker("City", selection:$city){
                  ForEach(["Delhi", "Mumbai", "Pune", "Kolkata"], id: \.self){
                     s in Text(s)
                  }
               }
            }
            Section{
               Toggle("Notification", isOn: $notification)
            }
         }.navigationTitle("Employee Data")
      }
   }
}   
#Preview {
   ContentView()
}

输出

Form

示例 2

以下 SwiftUI 程序创建一个包含页眉和页脚的简单表单。

import SwiftUI
struct ContentView: View {
   @State private var name: String = ""
   @State private var email: String = ""
   @State private var about: String = "Write about yourself..."
   @State private var notification = false
   @State private var city: String = "Delhi"

   var body: some View {
      NavigationStack{
         Form{
            Section{
               TextField("Enter Name", text: $name)
               TextField("Enter Email", text: $email)
               TextEditor(text: $about)
               Picker("City", selection:$city){
                  ForEach(["Delhi", "Mumbai", "Pune", "Kolkata"], id: \.self){
                     s in Text(s)
                  }
               }
            }header: {
               Text("Employee's details")
            }footer: {
               Text("Provide personal data")
            }
            Section{
               Toggle("Notification", isOn: $notification)
            }header: {
               Text("Setting Notification")
            }
         }.navigationTitle("Employee Data")
      }
   }
}   
#Preview {
   ContentView()
}

输出

Form
广告