【问题标题】:SwiftUI - Proceed to new view, from an alertSwiftUI - 从警报进入新视图
【发布时间】:2020-09-29 15:50:03
【问题描述】:

我是 SwiftUI 的新手。我有以下代码,当用户单击警报上的“继续”时,我想继续“ContentView2”

struct ContentView: View {

@State var alertIsShown: Bool

var myArray = ["Blue","Red","Pink","Yellow"]

var body: some View {
    
    NavigationView{
    
    List(0..<myArray.count) { i in
        Button(action: {
                print("Button tapped")
            alertIsShown = true
            
        }) {
            Text(myArray[i])
        }
        .alert(isPresented: $alertIsShown) {
            Alert(title: Text("You have chosen"), message: Text("Are you sure you want to go to contentview2?"), primaryButton: .destructive(Text("Proceed!")) {
                    print("Proceeding...")
                
                ///Solution?
                
                
            }, secondaryButton: .cancel())
            
        }
    }
    }
}

}

struct ContentView2 : View {
    var body: some View {
        Text("Im the second view")
// This will eventually say "Im the yellow view", based on the selection on CV1
    }
}

这可能吗?

【问题讨论】:

  • 是的,有可能。将警报移出列表,然后将不可见的 NavigationLink 放置在列表的背景中,并通过警报回调以编程方式激活它。试试看。

标签: swift swiftui swiftui-navigationlink


【解决方案1】:

这是一个有效的示例代码。但它始终会导航到 ContentView2,与您将单击列表中的哪个项目无关。

struct ContentView: View {
    
    @State var alertIsShown = false
    @State private var navigate = false
    
    var myArray = ["Blue","Red","Pink","Yellow"]
    
    var body: some View {
        
        NavigationView{
            ZStack {
                NavigationLink(destination: ContentView2(), isActive: $navigate){
                    EmptyView()
                }
                List(0..<myArray.count) { i in
                    Button(action: {
                        print("Button tapped")
                        alertIsShown = true
                    }) {
                        Text(myArray[i])
                    }
                    .alert(isPresented: $alertIsShown) {
                        Alert(title: Text("You have chosen"), message: Text("Are you sure you want to go to contentview2?"), primaryButton: .destructive(Text("Proceed!")) {
                            navigate.toggle()
                        }, secondaryButton: .cancel())
                        
                    }
                }
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2021-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    • 2013-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多