如何在SwiftUI的一个视图上显示两个警报?

时间:2019-09-23 20:07:25

标签: swift swiftui

我想在同一个Button视图上附加两个唯一的警报。当我使用下面的代码时,只有底部的警报起作用。

我正在macOS Catalina上使用Xcode 11的官方版本。

@State private var showFirstAlert = false
@State private var showSecondAlert = false

Button(action: {
    if Bool.random() {
        showFirstAlert = true
    } else {
        showSecondAlert = true
    }
}) {
    Text("Show random alert")
}
.alert(isPresented: $showFirstAlert) {
    // This alert never shows
    Alert(title: Text("First Alert"), message: Text("This is the first alert"))
}
.alert(isPresented: $showSecondAlert) {
    // This alert does show
    Alert(title: Text("Second Alert"), message: Text("This is the second alert"))
}

我希望将showFirstAlert设置为true时显示第一个警报,而我希望将showSecondAlert设置为true时显示第二个警报。当状态为true时,只有第二个警报显示,但是第一个警报什么也不做。

6 个答案:

答案 0 :(得分:7)

.alert(isPresented)的第二个调用将覆盖第一个。您真正想要的是一个Binding<Bool>来表示是否显示警报,以及应该在.alert(isPresented)之后从闭包中返回警报的某些设置。您可以为此使用Bool,但是我继续使用枚举来完成此操作,因为它扩展为两个以上的警报。

enum ActiveAlert {
    case first, second
}

struct ToggleView: View {
    @State private var showAlert = false
    @State private var activeAlert: ActiveAlert = .first

    var body: some View {

        Button(action: {
            if Bool.random() {
                self.activeAlert = .first
            } else {
                self.activeAlert = .second
            }
            self.showAlert = true
        }) {
            Text("Show random alert")
        }
        .alert(isPresented: $showAlert) {
            switch activeAlert {
            case .first:
                return Alert(title: Text("First Alert"), message: Text("This is the first alert"))
            case .second:
                return Alert(title: Text("Second Alert"), message: Text("This is the second alert"))
            }
        }
    }
}

答案 1 :(得分:4)

我改进了小本的答案。 您可以使用.alert( item:)代替.alert( isPresented:):

动态显示多个警报
struct AlertItem: Identifiable {
    var id = UUID()
    var title: Text
    var message: Text?
    var dismissButton: Alert.Button?
}

struct ContentView: View {

    @State private var alertItem: AlertItem?

    var body: some View {
        VStack {
            Button("First Alert") {
                self.alertItem = AlertItem(title: Text("First Alert"), message: Text("Message"))
            }
            Button("Second Alert") {
                self.alertItem = AlertItem(title: Text("Second Alert"), message: nil, dismissButton: .cancel(Text("Some Cancel")))
            }
            Button("Third Alert") {
                self.alertItem = AlertItem(title: Text("Third Alert"))
            }
        }
        .alert(item: $alertItem) { alertItem in
            Alert(title: alertItem.title, message: alertItem.message, dismissButton: alertItem.dismissButton)
        }
    }
}

答案 2 :(得分:1)

此解决方案有一个变体,它仅使用一个状态变量,而不使用两个状态变量。它利用了另一种.alert()形式而不是布尔型Identifiable形式的事实,因此可以在其中传递额外的信息:

struct AlertIdentifier: Identifiable {
    enum Choice {
        case first, second
    }

    var id: Choice
}

struct ContentView: View {
    @State private var alertIdentifier: AlertIdentifier?

    var body: some View {
        HStack {
            Button("Show First Alert") {
                self.alertIdentifier = AlertIdentifier(id: .first)
            }
            Button("Show Second Alert") {
                self.alertIdentifier = AlertIdentifier(id: .second)
            }
        }
        .alert(item: $alertIdentifier) { alert in
            switch alert.id {
            case .first:
                return Alert(title: Text("First Alert"),
                             message: Text("This is the first alert"))
            case .second:
                return Alert(title: Text("Second Alert"),
                             message: Text("This is the second alert"))
            }
        }
    }
}

答案 3 :(得分:0)

extension Alert:Identifiable{
    public var id:String { "\(self)" }
}
@State var alert:Alert?

Button(action: {
    if Bool.random() {
        alert = Alert(title: Text("Alert 1"))
    } else {
        alert = Alert(title: Text("Alert 2"))
    }
}) {
    Text("Show random alert")
}
.alert(item:$alert) { $0 }

答案 4 :(得分:0)

如果您有更复杂的逻辑(例如,来自 1 个按钮的多个警报),这是另一种灵活的方法。您基本上可以将 .alert 附加到任何 View 并将警报逻辑与这样的按钮分开:

EmptyView() 对我不起作用。在 Xcode 12.4 中测试

// loading alert
Text("")
    .alert(isPresented: $showLoadingAlert, content: {
        Alert(title: Text("Logging in"))
    })
    .hidden()

// error alert
Text("")
    .alert(isPresented: $showErrorAlert, content: {
        Alert(title: Text("Wrong passcode"), message: Text("Enter again"), dismissButton: .default(Text("Confirm")))
    })
    .hidden()

答案 5 :(得分:0)

对此有两种解决方案。将您的 .alert 附加到另一个视图,例如生成警报的按钮。这是最好的解决方案,但并不总是有效,具体取决于视图。另一个选项如下,与接受的答案相比,它可以显示任何警报。

@State var isAlertShown = false
@State var alert: Alert? {
    didSet {
        isAlertShown = alert != nil
    }
}

YourViews {
    Button(action: {
        alert = Alert(title: Text("BACKUP"), message: Text("OVERWRITE_BACKUP_CONFIRMATION"), primaryButton: .destructive(Text("OVERWRITE")) {
            try? BackupManager.shared.performBackup()
        }, secondaryButton: .cancel())
    }, label: {
        Text("Button")
    })
}
.alert(isPresented: $isAlertShown, content: {
    guard let alert = alert else { return Alert(title: Text("")) }
        
    return alert
})