我的SwiftUI视图未更新第三级的导航标题

chy5wohz  于 2023-01-25  发布在  Swift
关注(0)|答案(1)|浏览(100)

我准备了一个简单的三层示例:

struct Element: Identifiable {
    let id = UUID()
    let text: String
    init(text: String) {
        self.text = text
    }
}

struct FirstView: View {
    @State var elements = [Element(text: "a"), Element(text: "b")]
    var body: some View {
        NavigationView {
            List(elements) { element in
                NavigationLink {
                    SecondView()
                } label: {
                    VStack(alignment: .leading, spacing: 3, content: {
                        Text(element.text)
                            .font(.system(size: 12))
                            .foregroundColor(.white)
                    })
                }
            }
            .navigationTitle("First")
        }
    }
}

struct SecondView: View {
    @State var elements = [Element(text: "1"), Element(text: "2")]
    var body: some View {
        NavigationView {
            List(elements) { element in
                NavigationLink {
                    ThirdView()
                } label: {
                    VStack(alignment: .leading, spacing: 3, content: {
                        Text(element.text)
                            .font(.system(size: 12))
                            .foregroundColor(.white)
                    })
                }
            }
            .navigationTitle("Second")
        }
    }
}

struct ThirdView: View {
    @State var elements = [Element(text: "+"), Element(text: "-")]
    var body: some View {
        NavigationView {
            List(elements) { element in
                NavigationLink {
                    SecondView()
                } label: {
                    VStack(alignment: .leading, spacing: 3, content: {
                        Text(element.text)
                            .font(.system(size: 12))
                            .foregroundColor(.white)
                    })
                }
            }
            .navigationTitle("Third")
        }
    }
}

而这就是当我进入下一个级别时,Apple Watch中会发生的事情:
第一节第一节第一节第一节第一节第二节第一节
正如你在第三个视图中看到的,导航标题没有更新。为什么?
渲染也有问题吗?当我向下滑动第二个列表时,结果如下:

bqf10yzr

bqf10yzr1#

您只需要从SecondViewThirdView周围删除NavigationView,即

struct SecondView: View {
    @State var elements = [Element(text: "1"), Element(text: "2")]
    var body: some View {
        List(elements) { element in
            NavigationLink {
                ThirdView()
            } label: {
                VStack(alignment: .leading, spacing: 3, content: {
                    Text(element.text)
                        .font(.system(size: 12))
                        .foregroundColor(.white)
                })
            }
        }
        .navigationTitle("Second")
    }
}

如果您正在为watchOS 9.0+构建,则可能应该使用新的NavigationStack

相关问题