How to put a condition to NavigationLink? SWIFTUI
Asked Answered
R

2

8

I would like to put a condition to the NavigationLink.

I have two variable, and the NavigationLink as below.

  @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.

Repand answered 29/2, 2020 at 23:39 Comment(1)
do you mean, that it automatically open destination if score > target?Bort
T
21

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

    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

    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.)

    NavigationLink(destination: level2(), isActive: .constant(score > target)) {
    Text("Next Level") }

  • alternate is to use explicit state for activation
Trimetallic answered 1/3, 2020 at 4:32 Comment(1)
The only problem with the second one is it will change the color to be grayReporter
R
2

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")
}
Reporter answered 16/12, 2020 at 11:47 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.