在 SwiftUI 表单中如何使用 Picker(选择器)?

34 min read
  1. 在 SwiftUI 视图中,使用 Form 添加表单,然后在其中添加 Picker 视图。
struct ExampleView: View {
    // 定义选项数组
    let colors = ["Red", "Green", "Blue"]
    
    // 定义状态变量来跟踪所选的颜色
    @State private var selectedColor = 0
    
    var body: some View {
        Form {
            Picker(selection: $selectedColor, label: Text("Color")) {
                ForEach(0 ..< colors.count) {
                    Text(self.colors[$0])
                }
            }
        }
    }
}
  1. 通过添加 tag 属性,您可以将每个选项映射到不同的值或枚举:
enum ColorType: String, CaseIterable {
    case red = "Red"
    case green = "Green"
    case blue = "Blue"
}

struct ExampleView: View {
    // 定义状态变量来跟踪所选的颜色类型
    @State private var selectedColor = ColorType.red
    
    var body: some View {
        Form {
            Picker(selection: $selectedColor, label: Text("Color")) {
                ForEach(ColorType.allCases, id: \.self) {
                    Text($0.rawValue).tag($0)
                }
            }
        }
    }
}
  1. 如果您需要设置 Picker 的外观,可以使用 pickerStyle 属性。例如,如果您想使用轮廓样式的 Picker,可以将其设置为 PickerStyle()
struct ExampleView: View {
    // 定义选项数组
    let colors = ["Red", "Green", "Blue"]
    
    // 定义状态变量来跟踪所选的颜色
    @State private var selectedColor = 0
    
    var body: some View {
        Form {
            Picker(selection: $selectedColor, label: Text("Color")) {
                ForEach(0 ..< colors.count) {
                    Text(self.colors[$0])
                }
            }
            .pickerStyle(WheelPickerStyle()) // 设置 Picker 样式
        }
    }
}