Do that strategy, utilizing a NavigationPath
with the NavigationStack
, as proven, works for me. This code will ...make it so it programmatically opens the navigation view when including a brand new merchandise.
struct ContentView: View {
var physique: some View {
ListView()
}
}
struct ColorDetail: View {
var colour: Colour
var physique: some View {
Textual content(colour.description)
}
}
struct ListView: View {
@State var colours: [Color] = [.red] // <--- right here all colours have to be distinctive
@State var path = NavigationPath() // <-- right here
var physique: some View {
NavigationStack(path: $path) { // <-- right here
Checklist(colours, id: .self) { colour in // <-- right here
NavigationLink(colour.description, worth: colour)
}
.toolbar {
Button("+") {
let newColor = Colour.blue // <-- right here, a special colour
colours.append(newColor)
path.append(newColor) // <-- right here
}
}
.navigationDestination(for: Colour.self) { colour in
ColorDetail(colour: colour)
}
.navigationTitle("Colours")
}
}
}
EDIT-1:
Close to your new query, right here is the code that can assist you to change the Colour
within the ColorDetail
.
struct ContentView: View {
var physique: some View {
ListView()
}
}
struct ColorDetail: View {
@Binding var mycolor: MyColor
var physique: some View {
Textual content(mycolor.colour.description)
Picker("", choice: $mycolor.colour) {
ForEach([Color.black, Color.pink, Color.yellow, Color.green], id: .self) { colour in
Textual content(colour.description).tag(colour)
}
}
}
}
struct MyColor: Identifiable, Hashable {
let id = UUID()
var colour: Colour
}
struct ListView: View {
@State var myColors: [MyColor] = [MyColor(color: .red)]
@State var path = NavigationPath()
var physique: some View {
NavigationStack(path: $path) {
Checklist(myColors) { colour in
NavigationLink(colour.colour.description, worth: colour)
}
.toolbar {
Button("+") {
let newColor = MyColor(colour: .blue)
myColors.append(newColor)
path.append(newColor)
}
}
.navigationDestination(for: MyColor.self) { colour in
if let ndx = myColors.firstIndex(the place: {$0.id == colour.id}) {
ColorDetail(mycolor: $myColors[ndx])
}
}
.navigationTitle("Colours")
}
}
}