簡體   English   中英

如何使用 SwiftUI 顯示警報

[英]How to present an Alert with SwiftUI

SwiftUI我發現了Alert類型。 但我想知道如何用presentation方法來展示它。

初始化Alert非常簡單。 但是如何使用綁定呢?

struct ContentView : View {
    var body: some View {
        Button(action: {
            // Don't know how to use the `binding` below
            presentation(binding, alert: {
                Alert(title: Text("Hello"))
            })
        }, label: {
            Text("asdf")
        })
    }
}

綁定的類型為Binding<Bool>

.presentation()實際上在 Beta 4 中已被棄用。這是當前與.alert()修飾符一起使用的版本。

struct ContentView: View {
    @State var showsAlert = false
    var body: some View {
        Button(action: {
            self.showsAlert.toggle()
        }) {
            Text("Show Alert")
        }
        .alert(isPresented: self.$showsAlert) {
            Alert(title: Text("Hello"))
        }
    }
}

您可以使用@State變量作為綁定。 或者,您可以使用使用BindableObject@EnvironmentObject變量。

我認為您需要在根視圖上調用presentation才能使其工作,將其添加到StackGroup等似乎不起作用。

這個片段似乎可以解決問題。 請注意, @State變量在警報解除后設置為 false。

struct ContentView: View {

    @State var showsAlert = false

    var body: some View {
        Button(action: {
            self.showsAlert = true
        }, label: {
            Text("asdf")
        }).presentation($showsAlert, alert: {
            Alert(title: Text("Hello"))
        })
    }
}

帶有解雇和正常操作的完整警報代碼:

代碼:

import SwiftUI

struct ContentView: View {
    @State private var isAlert = false

    var body: some View {
            Button(action: {
                self.isAlert = true
            }) {
                Text("Click Alert")
                .foregroundColor(Color.white)
            }
            .padding()
            .background(Color.blue)
            .alert(isPresented: $isAlert) { () -> Alert in
                Alert(title: Text("iOSDevCenters"), message: Text("This Tutorial for SwiftUI Alert."), primaryButton: .default(Text("Okay"), action: {
                    print("Okay Click")
                }), secondaryButton: .default(Text("Dismiss")))
        }

    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

輸出:

Output

除了@tsp 的回答,要顯示帶有兩個按鈕的警報並處理按鈕點擊動作,您可以執行以下操作:

@State var showAlert = false

var body: some View {
  Button(action: {
    self.showAlert = true
  }) {
    Text("Show Alert")
  }
  .presentation($showAlert) {
      Alert(title: Text("Title"), message: Text("Message..."),
          primaryButton: .default (Text("OK")) {
            print("OK button tapped")
          },
          secondaryButton: .cancel()
      )
  }
}

結果:

在此處輸入圖片說明

這是呈現多個警報的解決方案。 適用於iOS14

struct YourView: View {
    enum AlertType: Identifiable {
        case first, second
        
        var id: Int {
            hashValue
        }
    }
    
    @State var alertType: AlertType?
    
    var body: some View {
        VStack {
            Button("Show alert #1") {
                alertType = .first
            }
            
            Button("Show alert #2") {
                alertType = .second
            }
        }
        .alert(item: $alertType) { type in
            switch type {
            case .first:
                return Alert(title: Text("First alert"))
            case .second:
                return Alert(title: Text("Second alert"))
            }
        }
    }
}

使用onTapGesture示例

struct MyRow: View {
    @State private var showingAlert = false

    var body: some View {
        HStack {
            Text("Hello")
            Text("World")
        }
        .onTapGesture {
            self.showingAlert = true
        }
        .alert(isPresented: $showingAlert, content: {
            Alert(title: Text("Title"), message: Text("Message"), dismissButton: .default(Text("OK")))
        })
    }
}

除了@thisIsTheFoxe 的回答之外,您還可以實現一個簡單的擴展:

延期

public extension View {
    func alert(isPresented: Binding<Bool>,
               title: String,
               message: String? = nil,
               dismissButton: Alert.Button? = nil) -> some View {

        alert(isPresented: isPresented) {
            Alert(title: Text(title),
                  message: {
                    if let message = message { return Text(message) }
                    else { return nil } }(),
                  dismissButton: dismissButton)
        }
    }
}

用法:

因此,您現在可以輕松使用它,例如:

struct ContentView: View {
    @State var showsAlert = false
    var body: some View {
        Button("Show Alert") {
            self.showsAlert.toggle()
        }
        .alert(isPresented: $showsAlert, title: "title", message: "Message") // <- Here
    }
}
struct ContentView: View {

    @State var aAlert = false

    var body: some View {
        Text("Alert").tapAction {
            self.aAlert = true
        }.presentation($aAlert, alert:{ Alert(title: Text("Alert"))})
    }
}
  struct ContentView: View {
        @State private var showingAlert = false
    
        var body: some View {
            Button("Show Alert") {
                showingAlert = true
            }
            .alert("Important message", isPresented: $showingAlert) {
                Button("First") { }
                Button("Second") { }
                Button("Third") { }
            }
        }
    }

在此處輸入圖像描述

用戶界面

首先創建基本警報:

Alert(title: Text("Alert title"), message: Text("Alert message"), dismissButton: .default(Text("Got it!")))

然后定義一個可綁定的條件,告知警報何時可見或不可見。 切換該條件以顯示/隱藏警報。

struct ContentView: View {
    @State private var showingAlert = false

    var body: some View {
        Button(action: {
            self.showingAlert = true
        }) {
            Text("Show Alert")
        }
        .alert(isPresented: $showingAlert) {
            Alert(title: Text("Important message"), message: Text("Wear sunscreen"), dismissButton: .default(Text("Got it!")))
        }
    }
}
public extension View {
    func alert(isPresented: Binding<Bool>,
               title: String,
               message: String? = nil,
               dismissButton: Alert.Button? = nil) -> some View {

        alert(isPresented: isPresented) {
            Alert(title: Text(title),
                  message: {
                    if let message = message { return Text(message) }
                    else { return nil } }(),
                  dismissButton: dismissButton)
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM