首页 > 解决方案 > @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?")))
      })
...

测试场景是:

  1. 点击 btn 2 - 没有任何反应
  2. 单击 btn 1 - 打开弹出窗口,isAlertVisible现在值为==true
  3. 再次单击 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之后,看起来有点像......这可能吗?

标签: swiftswiftui

解决方案


首先,您的代码不完整,例如您的 Button 2 没有操作。

其次,如果你想显示两个不同的警报,你应该使用两个不同的变量来显示它们。

第三,解释为什么在第二个按钮点击后你的值是假的。警报修饰符接受一个绑定来决定是否应该显示警报。这是一种双向绑定,这意味着它会更改代码中的状态,还会更改从系统创建的警报视图中的状态。如果您单击警报的关闭按钮,它会将变量的值更改回两个 false 以正确表示状态。

我希望这回答了你的问题。


推荐阅读