带 NavigationLink 的按钮和函数调用 SwiftUI

Button with NavigationLink and function call SwiftUI

我对带条件的 NavigationLinks 有疑问。它没有像我预期的那样做出反应。当用户单击按钮时,必须调用函数“test”并给出 return 值。如果 return 值为真,则“SheetView”必须直接打开,而无需单击 NavigationLink 文本。请有人能帮我解决这个问题。提前致谢

我制作了一个小的(样本)程序来展示这个问题。

import SwiftUI

struct LoginView: View {
   @State var check = false
   @State var answer = false
   
    var body: some View {
       NavigationView {
         VStack{
            Text("it doesn't work")
            Button(action: {
                answer = test(value: 2)
                if answer {
                    //if the return value is true then directly navigate to the sheetview
                    NavigationLink(
                        destination: SheetView(),
                        label: {
                            Text("Navigate")
                        })
                }
            }, label: {
                Text("Calculate")
            })
            
        
         }
       }
    }
    
    func test(value: Int) -> Bool {
     
            if value == 1 {
                check = false
            } else {
                print("Succes")
                check = true
            }
        
        return check
    }
       
}


struct SheetView: View {

    var body: some View {
        NavigationView {
            VStack{
                Text("Test")
                    .font(.title)
            }
        }
    }
}
struct LoginView: View {
   @State var check = false
   @State var answer = false
   
    var body: some View {
       NavigationView {
         VStack{
            Text("it doesn't work")
            Button(action: {
                answer = test(value: 2)
                //<= here
            }, label: {
                Text("Calculate")
            })
            
        
         }
         .sheet(isPresented: $answer, content: {  //<= here
            SheetView()
         })
       }
    }
    
    ...

如果您尝试呈现 sheet(因为您将导航目标称为 SheetView),那么 Yodagama 的答案有效,但如果您尝试导航到 SheetView 而不是呈现 sheet ,下面的代码可以做到这一点。

struct LoginView: View {
   @State var check = false
   @State var answer = false
   
    var body: some View {
       NavigationView {
         VStack{
            Text("it doesn't work")
            NavigationLink(destination: SheetView(), isActive: $answer, label: {
                Button(action: {
                    answer = test(value: 2)
                }, label: {
                    Text("Calculate")
                })
            })
            
            
        
         }
       }
    }
    
    func test(value: Int) -> Bool {
     
            if value == 1 {
                check = false
            } else {
                print("Succes")
                check = true
            }
        
        return check
    }
       
}


struct SheetView: View {

    var body: some View {
        NavigationView {
            VStack{
                Text("Test")
                    .font(.title)
            }
        }
    }
}