简体   繁体   English

如何为 NavigationLink 设置条件? 斯威夫特

[英]How to put a condition to NavigationLink? SWIFTUI

I would like to put a condition to the NavigationLink.我想为 NavigationLink 设置一个条件。

I have two variable, and the NavigationLink as below.我有两个变量,以及如下所示的 NavigationLink。

  @State var score = 0
  @State var target = 10

NavigationLink(destination: level2()) {     
  Text("Next Level")
 }

Is there a way to let the user go to the next level if the score is bigger than the target?如果分数大于目标,有没有办法让用户进入下一个级别?

Thanks.谢谢。

Well, your question can be interpreted differently...好吧,你的问题可以有不同的解释......

1) if you want to don't show the ability to go next until score is bigger that target at all, then it is 1)如果你不想表现出下一步的能力,直到分数大于那个目标,那么它是

if score > target { // link will appear to user only when true
  NavigationLink(destination: level2()) {     
    Text("Next Level")
  }
}

2) if you want to show link but don't allow to navigate until condition is true, then it is 2)如果你想显示链接但在条件为真之前不允许导航,那么它是

  NavigationLink(destination: level2()) {     
    Text("Next Level")
  }.disabled(score <= target)

3) if you want automatically navigate link when condition is true, then the possible variant is ( but note - in such case you need manually manipulate back-forward navigation, or disallow back, etc. ) 3)如果您想在条件为真时自动导航链接,则可能的变体是(但请注意 - 在这种情况下,您需要手动操作后退导航,或禁止后退等

  NavigationLink(destination: level2(), isActive: .constant(score > target)) {     
    Text("Next Level")
  }
  • alternate is to use explicit state for activation另一种方法是使用显式状态进行激活

In case you want to keep the color and present some alert when you tap you can use below hack:如果您想保持颜色并在点击时显示一些警报,您可以使用以下技巧:

NavigationLink(destination: EmptyView()) {
                HStack {
                    Circle()
  }
}
            .contentShape(Rectangle())
            .onTapGesture {
                print("ALERT MAYBE")
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM