热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

HowtopresentanAlertwithswiftUI

如何解决《HowtopresentanAlertwithswiftUI》经验,为你挑选了3个好方法。

In swiftUI I discovered the Alert type. But I wonder how to show it with the presentation method.

Initializing an Alert is pretty easy. But how to use the binding?

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

The binding is of type Binding



1> thisIsTheFox..:

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



2> tsp..:

您可以使用@State变量作为绑定。或者,您可以使用使用的@EnvironmentObject变量BindableObject

我认为你需要调用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"))
        })
    }
}



3> Kirit Modi..:

完整的警报代码,具有撤消和可采取的措施:

码:

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


推荐阅读
author-avatar
blg1202702934392
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有