SwiftUI Confirmation Dialogs的使用
xcode 13.4.1, swift 5.5, iOS 15.4
2022-08-17
SwiftUI增加了一個很方便的Confirmation Dialogs向使用者詢問是否確定的對話框。
1. 配合state bool變量,和confirmationDialog向使用者詢問是否確定的對話框:
import SwiftUI
struct ConfirmationDialog : View {
@State private var isPresentingAlert: Bool = false
var body: some View {
Button {
isPresentingAlert = true
} label: {
Label("Delete", systemImage: "trash")
.font(.largeTitle)
}
.confirmationDialog("Are you sure?", isPresented: $isPresentingAlert, actions: {
Button("Confirm", role: .destructive) {
print("Delete")
}
})
}
}
2. 另外也可以在使用者回答時增加一些提示信息,實作如下:
import SwiftUI
struct ConfirmationDialog : View {
@State private var isPresentingAlert: Bool = false
var body: some View {
Button {
isPresentingAlert = true
} label: {
Label("Delete", systemImage: "trash")
.font(.largeTitle)
}
.confirmationDialog("Are you sure?", isPresented: $isPresentingAlert, actions: {
Button("Confirm", role: .destructive) {
print("Delete")
}
}, message: {
Text("You can not undo this action!")
})
}
}