SwiftUI-从警报进入新视图

时间:2020-09-29 15:50:03

标签: swift swiftui swiftui-navigationlink

我是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
    }
}

这可能吗?

1 个答案:

答案 0 :(得分:0)

下面的示例代码正在运行。但是,它将始终导航到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())
                        
                    }
                }
            }
        }
    }
}