[英]Selection in NavigationLink is not working
I have the following code for my iPad app:我的iPad应用程序有以下代码:
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.按下链接可以完美地工作,它也会改变 DetailView。 I try to highlight the selected button, therefore I save the selectionIndex.
我尝试突出显示选定的按钮,因此我保存了 selectionIndex。
Unfortunately the selectionIndex sometimes resets to 0. What am I doing wrong?不幸的是 selectionIndex 有时会重置为 0。我做错了什么?
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).将
NavigationLink
包装到List
中可以更好地显示问题,因为 List 有自己的选择(此选择保留,但我自己的var selectionIndex
重置)。
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.
使用 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)
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.