SwiftUI Picker optional binding

发布
更新
字数 260
阅读 2 分钟
阅读量 875

在 SwiftUI 中使用 Picker 控件有多种样式选择,非常方便

extension PickerStyle {
    // iOS 13.0+
	// macOS 10.15+
	// Mac Catalyst 13.0+
	// tvOS 13.0+
	// watchOS 6.0+
    static var automatic: DefaultPickerStyle
    // iOS 14.0+
	// macOS 11.0+
	// Mac Catalyst 14.0+
	// tvOS 14.0+
	// watchOS 7.0+
    static var inline: InlinePickerStyle
    // iOS 14.0+
	// macOS 11.0+
	// Mac Catalyst 14.0+
    static var menu: MenuPickerStyle
    // iOS 16.0+
	// Mac Catalyst 16.0+
	// tvOS 16.0+
	// watchOS 9.0+
    static var navigationLink: NavigationLinkPickerStyle
    // macOS 10.15+
    static var radioGroup: RadioGroupPickerStyle
    // iOS 13.0+
	// macOS 10.15+
	// Mac Catalyst 13.0+
	// tvOS 13.0+
    static var segmented: SegmentedPickerStyle
    // iOS 13.0+
	// Mac Catalyst 13.0+
	// watchOS 6.0+
    static var wheel: WheelPickerStyle
}

使用 Picker 时,选项实现 Identifiable 后,ForEach 可以自动为每项的 tag 赋值。

enum Flavor: String, CaseIterable, Identifiable {
    case chocolate, vanilla, strawberry
    var id: Self { self }
}

@State private var selectedFlavor: Flavor = .chocolate

Picker("Flavor", selection: $selectedFlavor) {
    ForEach(Flavor.allCases) { flavor in
        Text(flavor.rawValue.capitalized)
    }
}

现在用户可以不选择任何的口味了,因此我们需要修改 selectedFlavor 为可选值,并手动转换 Picker 选项的 tag as Flavor?

@State private var selectedFlavor: Flavor?

Picker("Flavor", selection: $selectedFlavor) {
    ForEach(Flavor.allCases) { flavor in
		Text("None").tag(nil as Flavor?)
        Divider()
        Text(flavor.rawValue.capitalized).tag(flavor as Flavor?)
    }
}