Picker trong SwiftUI
1. Cơ bản
@State private var selection = "Red"
let colors = ["Red", "Green", "Blue"]
Picker("Color", selection: $selection) {
ForEach(colors, id: \.self) { color in
Text(color).tag(color)
}
}2. Picker Styles
// Menu (default)
Picker("Color", selection: $selection) { }
.pickerStyle(.menu)
// Segmented
Picker("Size", selection: $size) { }
.pickerStyle(.segmented)
// Wheel
Picker("Number", selection: $number) { }
.pickerStyle(.wheel)
// Inline (in List)
Picker("Option", selection: $option) { }
.pickerStyle(.inline)3. Với Enum
enum Size: String, CaseIterable {
case small, medium, large
}
@State private var size: Size = .medium
Picker("Size", selection: $size) {
ForEach(Size.allCases, id: \.self) { size in
Text(size.rawValue.capitalized)
}
}
.pickerStyle(.segmented)4. DatePicker
@State private var date = Date()
DatePicker("Date", selection: $date)
DatePicker("Time", selection: $date, displayedComponents: .hourAndMinute)
DatePicker("Date", selection: $date, in: Date()...) // Future only5. ColorPicker
@State private var color = Color.blue
ColorPicker("Theme Color", selection: $color)
ColorPicker("Color", selection: $color, supportsOpacity: false)📝 Tóm tắt
| Style | Appearance |
|---|---|
.menu | Dropdown |
.segmented | Segment control |
.wheel | Spinning wheel |
.inline | Inline in list |
Last updated on