swift - @State 属性如何不保存状态?
问题描述
我是 iOS 新手。我正在尝试做一些测试 UI 以了解这里的一些基本内容,我的问题是 - 我的屏幕上有两个按钮
...
@State private var isAlertVisible: Bool = false
...
Button("1") {
isAlertVisible = true
}
.alert(isPresented: $isAlertVisible, content: {
return Alert(title: Text("Hello there!"), message: Text("This is my first pop-up"), dismissButton: .default(Text("Awesome!")))
})
Button("2") {
}
.alert(isPresented: $isAlertVisible, content: {
return Alert(title: Text("Who's There?"), message: Text("Little old lady."), dismissButton: .default(Text("Little old lady who?")))
})
...
测试场景是:
- 点击 btn 2 - 没有任何反应
- 单击 btn 1 - 打开弹出窗口,
isAlertVisible
现在值为==true
- 再次单击 btn 2 - 以
isAlertVisible
现在的值打开弹出窗口==true
但实际结果是单击按钮 2 被忽略,在调试中我看到该isAlertVisible
值仍然为 false。
问题是——为什么在点击 btn 1 状态后isAlertVisible
没有变为真?
UPD
我想提出这样的问题
... @State private var isAlertVisible: Bool = false
...
Button("1") {
isAlertVisible = true
}
.alert(isPresented: $isAlertVisible, content: {
return Alert(title: Text("Hello there!"), message: Text("This is my first pop-up"), dismissButton: .default(Text("Awesome!")))
})
假设我有一个 btn 并且第一次单击它,所以我设置了调试(为了查看值)并且我希望在我第一次单击之后isAlertVisible
是真的,但是当我在调试器中进行第二次单击时我看到了价值仍然是假的。在单击将值从true返回到默认状态为false之后,看起来有点像......这可能吗?
解决方案
首先,您的代码不完整,例如您的 Button 2 没有操作。
其次,如果你想显示两个不同的警报,你应该使用两个不同的变量来显示它们。
第三,解释为什么在第二个按钮点击后你的值是假的。警报修饰符接受一个绑定来决定是否应该显示警报。这是一种双向绑定,这意味着它会更改代码中的状态,还会更改从系统创建的警报视图中的状态。如果您单击警报的关闭按钮,它会将变量的值更改回两个 false 以正确表示状态。
我希望这回答了你的问题。
推荐阅读
- python - 创建一个非常简单的不和谐机器人的最佳方法=
- system.reactive - ToObservable 在某些情况下不会触发
- node.js - Sails v1 中无法识别的修饰符“_bsontype”
- r - 当内部有嵌套函数时,如何在 R 中以编程方式创建函数?
- tsql - 使用 BULK 从网络文件导入 Proc 定义
- swift - 在 macOS 中结合 3D 和 2D
- react-native - react-native中的不规则形状视图?
- ruby - get class name of the immediate class, not full class name. ruby
- mysql - 从一张桌子上得到第 n 高的薪水有一个我不明白的代码
- flask - Flask 可以在不使用 Celery 的情况下处理多个后台任务