0

我对带有条件的 NavigationLinks 有疑问。它没有反应我的预期。当用户单击按钮时,必须调用函数“test”并给出返回值。如果返回值为 true,则必须直接打开“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)
            }
        }
    }
}
4

2 回答 2

3

如果您尝试显示工作表(因为您调用了导航目标 SheetView),Yodagama 的答案有效,但如果您尝试导航到 SheetView 而不是显示工作表,则以下代码将执行此操作。

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)
            }
        }
    }
}
于 2021-06-24T15:31:46.637 回答
0
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()
         })
       }
    }
    
    ...
于 2021-06-24T15:26:38.813 回答