To-do List, creating a new view from navigation link

So I'm making this to do list app for myself and what I want to do is I want people do users to add to-dos and being able to click on them using navigation link, which takes them to a new view.

The problem here is i don't know how to create a new view everytime user creates a content in list.

How would i do this?

Answered by Vision Pro Engineer in 773210022

Hi @yh29 ,

To do this, you will need a NavigationStack to push new views onto. You'll want to iterate over your data (let's say it's an array of Strings) in a List or ForEach, and then use a NavigationLink which will automatically open a new view with the data you pass in. For example:

@State private var data: [String] = ["one", "two", "three"]
var body: some View {
 NavigationStack {
  List(data, id: \.self) { item in
       NavigationLink(item, value: item)
   }
   .navigationDestination(for: String.self) { toDoItem in
    Text(toDoItem)
   }
 }
}

Here, I've used the NavigationDestination modifier, which navigates to a new view with the data passed in for the presented data type. Since the value I pass in the NavigationLink is a String, I make sure that for any String that is presented, the destination will be a view containing text with that String. Check out the linked documentation for more examples!

A. Open a new view with Sheet or equivalent?

B. Navigate to a new View to NavigateLink?

C. Use NavigationSplitView?

I'm thinking of B but if B doesn't work, A could work too

I'm thinking of B but if B doesn't work, A could work too

Accepted Answer

Hi @yh29 ,

To do this, you will need a NavigationStack to push new views onto. You'll want to iterate over your data (let's say it's an array of Strings) in a List or ForEach, and then use a NavigationLink which will automatically open a new view with the data you pass in. For example:

@State private var data: [String] = ["one", "two", "three"]
var body: some View {
 NavigationStack {
  List(data, id: \.self) { item in
       NavigationLink(item, value: item)
   }
   .navigationDestination(for: String.self) { toDoItem in
    Text(toDoItem)
   }
 }
}

Here, I've used the NavigationDestination modifier, which navigates to a new view with the data passed in for the presented data type. Since the value I pass in the NavigationLink is a String, I make sure that for any String that is presented, the destination will be a view containing text with that String. Check out the linked documentation for more examples!

To-do List, creating a new view from navigation link
 
 
Q