如何向用户显示警报? [英] How to present alert to User?

查看:34
本文介绍了如何向用户显示警报?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

结果:

这篇关于如何向用户显示警报?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆