[英]Inform view that alert OK button is clicked in swiftUI
我創建了一個ViewModifier
來顯示帶有 2 個按鈕的警報。 如何通知我的 ContentView 單擊確定按鈕,以便我可以執行按鈕操作?
示例代碼:ShowAlert 是我的自定義 ViewModifier
struct ShowAlert: ViewModifier {
@Binding var showingAlert: Bool
let title: String
let message: String
func body(content: Content) -> some View {
content
.alert(isPresented: $showingAlert) { () -> Alert in
Alert(title: Text(title), message: Text(message),
primaryButton: .default (Text("OK")) {
print("OK button tapped")
//How to trigger ok button clicked event to my content view
},secondaryButton: .cancel())
}
}
}
查看實施
ScrollView {
....
}.navigationBarTitle("Click")
.navigationBarItems(trailing: Button(action: {
self.showAlert = true
}) {
Image(systemName: "lock")
}.modifier(ShowAlert(showingAlert: $showAlert, title: "", message: "Are you sure you want to Logout"))
這是一個將回調傳遞給修飾符的解決方案演示。 使用 Xcode 11.4 / iOS 13.4 進行測試。
struct ShowAlert: ViewModifier {
@Binding var showingAlert: Bool
let title: String
let message: String
var callback: () -> () = {} // << here !!
func body(content: Content) -> some View {
content
.alert(isPresented: $showingAlert) { () -> Alert in
Alert(title: Text(title), message: Text(message),
primaryButton: .default (Text("OK")) {
print("OK button tapped")
self.callback() // << here !!
},secondaryButton: .cancel())
}
}
}
// Demo view
struct TestAlertModifier: View {
@State private var showAlert = false
@State private var demoLog = "Wait for alert..."
var body: some View {
NavigationView {
ScrollView {
Text(demoLog)
}.navigationBarTitle("Click")
.navigationBarItems(trailing: Button(action: {
self.showAlert = true
}) {
Image(systemName: "lock")
}.modifier(ShowAlert(showingAlert: $showAlert, title: "",
message: "Are you sure you want to Logout", callback: confirmAlert)))
}
}
private func confirmAlert() {
self.demoLog = "Tapped - OK"
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.