【问题标题】:SwiftUI Alert showing twice despite only setting its State variable once尽管只设置了一次状态变量,但 SwiftUI 警报显示两次
【发布时间】:2021-06-29 07:45:01
【问题描述】:

在我的 swiftUI MacOS 应用程序中,我通过将绑定到警报的 State 变量设置为 true 来显示警报。但是在解除警报后,它会再次显示,我必须再次解除它。

我确实看到帖子here 有同样的问题,但似乎没有结论。

这里是警报:

.alert(isPresented: $showingCantDeleteInstanceAlert) {
    Alert(
        title: Text("Unable to delete instance \"\(instances[selectedInstanceIndex ?? 0].wrappedName)\""),
        message: Text("Can't have zero instances. Create a new instance to delete this one."),
        dismissButton: .default(Text("OK"))
    )
}

下面是设置 State 变量的代码:

if instances.count <= 1 {
    showingCantDeleteInstanceAlert = true
    return
}

我什至尝试在解除警报时手动将变量设置为 false:

.alert(isPresented: $showingCantDeleteInstanceAlert) {
    Alert(
        title: Text("Unable to delete instance \"\(instances[selectedInstanceIndex ?? 0].wrappedName)\""),
        message: Text("Can't have zero instances. Create a new instance to delete this one."),
        dismissButton: .default(Text("OK")) {
            showingCantDeleteInstanceAlert = false
        }
    )
}

但问题依然存在,警报仍然显示两次...

有什么想法吗?

【问题讨论】:

    标签: arrays swift binding alert


    【解决方案1】:

    我想我可以看到问题

    if instances.count <= 1 {
        showingCantDeleteInstanceAlert = true
        return
    }
    

    需要

    if instances.isEmpty {
        showingCantDeleteInstanceAlert = true
        return
    }
    

    我会解释一下,它相当简单,但无论如何我都会解释一下,你所做的 &lt;= 在这种情况下可能会导致你的问题。 因此,从instances.count 开始将是 0,然后您会显示一个警报,现在 instances.count 是 1,当您执行检查 instances.count &lt;= 1 时,它将为真,因为该检查显示 if instances.count is less than or equal to 1 then proceed,因为 instances.count 是等于 1。

    另外,请确保将 showingCantDeleteInstanceAlert 设置回 false

    【讨论】:

    • 如果是这种情况,那么我建议改用isEmpty
    • 我已经更新了我的答案。 isEmpty 更好
    • 感谢您的回复。不幸的是,这并没有解决它, isEmpty 没有工作,因为我需要确保永远不会有 0 个实例,所以这段代码在我删除一个实例之前运行。如果只有 1 个实例,它需要运行,因为在这种情况下我不希望它被删除。此外,触发警报的函数只运行一次,我可以通过在showingCantDeleteInstanceAlert = true 下放置一个 print() 来验证这一点。这似乎肯定是警报的问题,而不是触发它的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-25
    • 2020-06-22
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多