SwiftUI中的Picker用于从一个值选择器中选择单个值。它的主要特点包括:
- 数据绑定
- 数据提供
- 内置丰富的样式
数据绑定
通过@State绑定来跟踪选中的Picker值。
@State var selected = "One"
Picker("Title", selection: $selected) {
Text("One").tag("One")
Text("Two").tag("Two")
}
数据提供
使用数组来提供数据源
let options = [Color.red, Color.blue, Color.orange]
@State private var option = Color.red
Picker("automatic style", selection: $option) {
ForEach(options, id: \.self) { option in
Text(option.description)
.foregroundColor(option)
.tag(option)
}
}.pickerStyle(.automatic)
使用枚举来提供数据源
enum Colors: String, CaseIterable {
case red, blue, gray
}
@State var selectedColor: Colors = Colors.blue
Picker("Selected a color", selection: $selectedColor) {
ForEach(Colors.allCases, id: \.self) { color in
Text(color.rawValue).tag(color)
}
}
内置丰富的样式
.inline
.menu
.segmented
上述就是picker简单介绍。
大家有什么看法呢?欢迎留言讨论。
公众号:RobotPBQ