I have the following code for my iPad app:
struct ContentView: View {
@State var selectionIndex: Int? = nil
var body: some View {
NavigationView {
VStack {
ForEach(0..<5) { tag in
NavigationLink("Link \(tag)", destination: DetailView(name: "View \(tag)"), tag: tag, selection: self.$selectionIndex)
.foregroundColor((self.selectionIndex ?? 0) == tag ? Color.red : Color.black)
}
}
}
}
}
struct DetailView: View {
var name: String
var body: some View {
Text(self.name)
}
}
Pressing the links works perfectly and also it changes the DetailView. I try to highlight the selected button, therefore I save the selectionIndex.
Unfortunately the selectionIndex sometimes resets to 0. What am I doing wrong?
EDIT
Wrapping the NavigationLink
into a List
shows the problematic better, as the List has it's own selection (this selection stays, but my own var selectionIndex
resets).
NavigationView {
List {
ForEach(0..<5) { tag in
NavigationLink("Link \(tag)", destination: DetailView(name: "View \(tag)"), tag: tag, selection: self.$selectionIndex)
.foregroundColor((self.selectionIndex ?? 0) == tag ? Color.red : Color.black)
}
}
}
See this screen:
Well, this of course looks like a bug, but they do what they documented - show destination of selected tag, no more. Anyway, probably worth submitting feedback.
Here is a working workaround. Tested with Xcode 11.4.
@State var selectionIndex: Int? = nil
@State var highlighted: Int? = nil // << explicit !!
var body: some View {
NavigationView {
VStack {
ForEach(0..<5) { tag in
NavigationLink("Link \(tag)", destination:
PadDetailView(name: "View \(tag)").onAppear { self.highlighted = tag },
tag: tag, selection: self.$selectionIndex)
.foregroundColor(self.highlighted == tag ? Color.red : Color.black)
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.