【问题标题】:SwiftUI - Alert doesn't dismiss. It keeps coming backSwiftUI - 警报不会关闭。它不断回来
【发布时间】:2021-02-11 14:25:16
【问题描述】:
.alert(isPresented:$showingAlert) {
        Alert(
            title: Text("Are you sure you want to delete this?"),
            message: Text("There is no undo"),
            primaryButton: .destructive(Text("Delete")) {
                //(using showingAlert = false doesn't help.)
                //(leaving this section empty doesn't help as well so any code written here is unrelated.)
                unrelatedCode()
            },
            secondaryButton: .cancel()
        )
    }

为什么无论我按哪个按钮,此代码都会导致警报返回屏幕? 这是一个更容易理解的视频:https://imgur.com/a/hN5yC3t

编辑:我猜这似乎是 swiftui 方面的一个错误。我想我会解决它。

编辑 2:可能与问题相关的所有内容:

struct EditProcessView: View {
@State var problem:Bool = false
@State var showingAlert = false

@State var text = ""
var body: some View {
    Form{
        //2 unrelated pickers.
        
        //Unrelated textfield
        Button(“Delete”){
            showingAlert = true //Are you sure you want to delete this? Button.
        }
    }
    .frame(minWidth: 200, idealWidth: 200)
    .alert(isPresented: $problem) {Alert.init(title: Text(“Fill the textfield with a number.“))}
    .alert(isPresented:$showingAlert) {
        Alert(
            title: Text("Are you sure you want to delete this?"),
            message: Text("There is no undo."),
            primaryButton: .destructive(Text("Delete")) {
                //Unrelated code.
               
            },
            secondaryButton: .cancel()
        )
    }
}

【问题讨论】:

  • 可能与视图层次结构有关。尝试将 .alert() 移到视图中的其他位置?
  • 首先检查你的 unrelatedCode() 方法是否改变了showingAlert。
  • @Yodagama 删除 unrelatedCode() 并将其用作无功能的警报框也会导致此问题,因此它不能是 unrelatedCode()
  • @Shazniq (1) 当我运行此代码并切换 $showingAlert 时,它只出现一次。 (2) 在同一个视图中不能有两个 .alerts() 。而是使用一个警报并使标题/消息动态化。
  • 所有按钮触发?可能需要PlainButtonStyle,常见问题Bordless or Plain

标签: swiftui


【解决方案1】:

当用户点击警报中的一个按钮时,警报会自行解除,方法是将绑定的 isPresented 值设置回 false。

@State private var showAlert = false
var body: some View {
    Button("Tap to show alert") {
        showAlert = true
    }
    .alert(isPresented: $showAlert) {
        Alert(
            title: Text("Unable to Save Workout Data"),
            message: Text("The connection to the server was lost."),
            primaryButton: .default(
                Text("Try Again"),
                action: saveWorkoutData
            ),
            secondaryButton: .destructive(
                Text("Delete"),
                action: deleteWorkoutData
            )
        )
    }
}

【讨论】:

    猜你喜欢
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-01
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多