SwiftUI Lists & Forms Form
SwiftUI Lists & Forms: Form
Group input controls with Form to build settings and data-entry screens.
Example: Basic Form
Example
import SwiftUI
struct FormBasicDemo: View {
@State private var name = ""
@State private var notifications = true
var body: some View {
Form {
Section(header: Text("Profile")) { TextField("Name", text: $name) }
Section(header: Text("Preferences")) { Toggle("Notifications", isOn: $notifications) }
}
}
}
import SwiftUI
struct ContentView: View { var body: some View { FormBasicDemo() } }
import SwiftUI
@main
struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } } }
Example: Validation & Submit
Example
import SwiftUI
struct FormAdvancedDemo: View {
@State private var email = ""
@State private var accepted = false
var valid: Bool { email.contains("@") && accepted }
var body: some View {
Form {
Section(header: Text("Account")) {
TextField("Email", text: $email).keyboardType(.emailAddress)
Toggle("Accept Terms", isOn: $accepted)
}
Section { Button("Submit") { } .disabled(!valid) }
}
}
}
import SwiftUI
struct ContentView: View { var body: some View { FormAdvancedDemo() } }
import SwiftUI
@main
struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } } }