Picker in SwiftUI

466 阅读1分钟

SwiftUI中的Picker用于从一个值选择器中选择单个值。它的主要特点包括:

  1. 数据绑定
  2. 数据提供
  3. 内置丰富的样式

数据绑定

通过@State绑定来跟踪选中的Picker值。

@State var selected = "One" 

Picker("Title", selection: $selected) {
  Text("One").tag("One")
  Text("Two").tag("Two")
}

image.png

数据提供

使用数组来提供数据源

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)

image.png

使用枚举来提供数据源

 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)
                }
            }

image.png

内置丰富的样式

.inline

image.png

.menu

image.png

.segmented

image.png

上述就是picker简单介绍。

大家有什么看法呢?欢迎留言讨论。
公众号:RobotPBQ