How to present alert to User?

2019-08-10 21:46发布

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...

2条回答
等我变得足够好
2楼-- · 2019-08-10 22:12

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

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

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"))
        }
    }

}

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

Result:

enter image description here

查看更多
再贱就再见
3楼-- · 2019-08-10 22:24

To display an alert with two buttons you can do like below:

@State var showAlert = false

let alert = Alert(title: Text("Title"), message: Text("Alert message"),
  primaryButton: Alert.Button.default(Text("OK"), 
    onTrigger: {
      print("OK button tapped")
    }
  ), 
  secondaryButton: Alert.Button.cancel()
)

var body: some View {

  NavigationView {
    Text("Content")
      .navigationBarItems(trailing: Button(action: {
        self.showAlert = true
      }, label: {
        Text("Show Alert")
      }).presentation(self.$showAlert, alert: {
        return alert
      })
    )
  }
}

Result:

enter image description here

查看更多
登录 后发表回答