如何向用户显示警报?

问题描述:

我想问你如何向用户显示警报.我刚试过:

I would like to ask you how can I show alert to user. I just tried:

.navigationBarItems(trailing: Button(action: {
      let alert = Alert(title: Text("Add category"), message: Text("Do you want add category?"), primaryButton: Alert.Button.default(Text("Yes"), onTrigger: {
           self.sceneries[0].sceneries.append(Scenery(name: "Name", imageName: "1"))
      }), secondaryButton: Alert.Button.cancel())
      self.presentation(self.$isShownAlert) { () -> Alert in
           return alert
      }
 }, label: {
      Text("Add category")
}))

但它告诉我它没有使用并且没有出现警报......

But it shows me that it's unused and alert didn't appear...

您需要在应显示警报的视图之上调用 presentation API.

You need to call presentation API on top of the view that should display the alert.

实现此目的的最佳方法是拥有一个 @State 变量,它告诉 SwiftUI 是否应显示警报.

The best way to accomplish this is to have a @State variable, that tells SwiftUI whether the alert should be displayed or not.

Button 动作然后会将其设置为 true,从而使 body 无效,并触发视图重建.

The Button action would then set it to true, thus invalidating body, and triggering a view rebuilding.

struct ContentView : View {

    @State var showAlert = false

    var body: some View {
        NavigationView {
            List(0...10) { value in
                Text(verbatim: "\(value)")
            }
            .navigationBarItems(leading: EmptyView(), trailing: Button(action: {
                self.showAlert = true
            }) {
                Text(verbatim: "Show alert")
            })
            .navigationBarTitle(Text(verbatim: "A List"))
        }
        .presentation($showAlert) {
            return Alert(title: Text(verbatim: "An Alert"))
        }
    }

}

在本例中,按钮将 @State 设置为 true,并在导航视图上调用 presentation.

In this example, the button sets the @State to true, and presentation is called on the navigation view.

结果: