NavigationLink destination - Set view programmatically

Hi,

I am programming a treasure hunt for my daughter.

The main view consists of several NavigationLinks as image. If you click on a task (=image), the view of the individual task comes. Each tasks view is different.

HStack(alignment: .top, spacing: 20) {

	NavigationLink(
			destination: Task01View()
	) {
  	 Text("1. Aufgabe")
       .font(.custom("Chalkduster", fixedSize: 16))
       .foregroundColor(Color(UIColor.brown))
	
		// ...  
	}
	
	NavigationLink(
			destination: Task02View()
	) {
  	 Text("2. Aufgabe")
       .font(.custom("Chalkduster", fixedSize: 16))
       .foregroundColor(Color(UIColor.brown))
	
		// ...  
	}
	
	NavigationLink(
			destination: Task03View()
	) {
  	 Text("3. Aufgabe")
       .font(.custom("Chalkduster", fixedSize: 16))
       .foregroundColor(Color(UIColor.brown))
	
		// ...  
	}
	
	// More NavigationLinks
}

The app has 24 tasks. There is a separate view for each task.

Currently I am hard-coding the navigation links into the source code.

However, my goal is to use a For loop to generate the images with the NavigationLinks. But my problem is the destination parameter in the NavigationLink.

How can I set the required view (e.g. Task01View or Task04View) automatically?

My idea.

for task in (1...6) {
		NavigationLink(
								destination: ??? // Here is my problem
				) {
					Text("\(task). Aufgabe")
						.font(.custom("Chalkduster", fixedSize: 16))
						.foregroundColor(Color(UIColor.brown))
}

Thanks in advance for the support.

Answered by piro299 in 691064022

Thank you very much. The solution is great and simple. Now I know :-)

Thanks a million!

As far as I read your requirements, you do not seem to have many choices.

One possible way, prepare a generic TaskView:

struct TaskView: View {
    let number: Int
    
    var body: some View {
        switch number {
        case 1:
            Task01View()
        case 2:
            Task02View()
        case 3:
            Task03View()
        //...
        default:
            EmptyView()
        }
    }
}

And use it like this:

            ForEach(0...6, id: \.self) { task in
                NavigationLink(
                    destination: TaskView(number: task)
                ) {
                    Text("\(task). Aufgabe")
                        .font(.custom("Chalkduster", fixedSize: 16))
                        .foregroundColor(Color(UIColor.brown))
                }
            }
Accepted Answer

Thank you very much. The solution is great and simple. Now I know :-)

Thanks a million!

NavigationLink destination - Set view programmatically
 
 
Q