NavigationLink 中的选择不起作用 [英] Selection in NavigationLink is not working

查看:26
本文介绍了NavigationLink 中的选择不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 iPad 应用有以下代码:

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)
    }
}

按下链接效果很好,它也会改变 DetailView.我尝试突出显示所选按钮,因此我保存了 selectionIndex.

Pressing the links works perfectly and also it changes the DetailView. I try to highlight the selected button, therefore I save the selectionIndex.

不幸的是,selectionIndex 有时会重置为 0.我做错了什么?

Unfortunately the selectionIndex sometimes resets to 0. What am I doing wrong?

编辑

NavigationLink 包装到 List 中可以更好地显示问题,因为 List 有它自己的选择(这个选择保持不变,但我自己的 var selectionIndex重置).

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)
                }
            }
        }

看到这个画面:

推荐答案

嗯,这当然看起来像一个错误,但他们做他们记录的事情 - 显示所选标签的目的地,没有更多.无论如何,可能值得提交反馈.

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.

这是一个可行的解决方法.使用 Xcode 11.4 测试.

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)
            }
        }
    }
}

这篇关于NavigationLink 中的选择不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆