swiftui - 带有“空”和 0...9 的 Swift UI 多个选择器
问题描述
我想创建一个选择器,其中包含三个数字,每个数字从 0..9 和“空”中选择,然后获取这些值,例如 number1 number2 和 number3
找到了一种与 0..9 一起使用的方法,但我怎么能也使用一个空的空白选择可以有空的值
问候亚历克斯
解决方案
我在下面做了一个简单的例子来说明你将如何做到这一点。它允许您选择任何数字,并将空值标记为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?)
}
}
}
}
}
推荐阅读
- reactjs - 如何访问 useEffect() 挂钩中的变量
- python - 如何生成三个异常点,使它们明显远离 python 中的正常数据?
- python - Kivy 程序有一个 TypeError
- cudf - cuDF GPU 利用率低
- html - 鼠标移出时立即结束 CSS 过渡
- c# - 如何在 Unity 中使用按钮截取画布的屏幕截图
- sharepoint - 在 Microsoft Flow/Power Automate 中从电子邮件获取附件的问题
- python - 有没有比循环遍历数据框更好的方法将数据框转换为“真值表”?
- python - 集群 id 列中缺少值的问题
- mongodb - 使用 docker-entrypoint-initdb.d 创建的 Mongodb 用户不会保留在数据库中