首页 > 解决方案 > 带有“空”和 0...9 的 Swift UI 多个选择器

问题描述

我想创建一个选择器,其中包含三个数字,每个数字从 0..9 和“空”中选择,然后获取这些值,例如 number1 number2 和 number3

找到了一种与 0..9 一起使用的方法,但我怎么能也使用一个空的空白选择可以有空的值

问候亚历克斯

标签: swiftuipicker

解决方案


我在下面做了一个简单的例子来说明你将如何做到这一点。它允许您选择任何数字,并将空值标记为nil。这应该使从而不是number1 number2 and number3等中获取值变得更加容易。

struct ContentView: View {
    
    @State private var selection: Int?
    private var formattedSelection: String {
        selection != nil ? String(selection!) : "Empty"
    }
    
    var body: some View {
        VStack {
            Text("Selection:  \(formattedSelection)")
            
            Picker("Select number", selection: $selection) {
                Text("Empty").tag(nil as Int?)
                
                // Ranges from 0 to 9
                ForEach(0 ..< 10) { value in
                    Text(String(value)).tag(value as Int?)
                }
            }
        }
    }
}

推荐阅读