首页 > 解决方案 > List 中的 SwiftUI NavigationLinks 加载 NSViewDelegate/NSViewControllerDelegate 两次

问题描述

我目前正在涉足 macOS 开发,并尝试将一些 AppKit 组件包装到 SwiftUI 中。我正在使用带有NavigationLinks的侧边栏导航List。当使用NSViewRepresentableorNSViewControllerRepresentable作为目的地时,makeNSView/makeNSViewController方法被调用两次。我想这是一个错误,因为当我将NavigationLinks 直接包装在NavigationView? 有没有其他人遇到这个问题并且可以帮助我解决问题,直到它被修复?

重现的最小实现:

import SwiftUI

struct ViewRepresentable: NSViewRepresentable {
    let title: String
    
    
    func updateNSView(_ nsView: NSView, context: Context) {
    }

    func makeNSView(context: Context) -> NSView {
        print("\(title) make view called")
        return NSView()
    }
}

struct ContentView: View {
    enum NavigationItem {
        case sel1
        case sel2
    }

    @State private var selection: NavigationItem? = .sel1

    var body: some View {
        NavigationView {
            List(selection: $selection) {
                NavigationLink(
                        destination: EmptyView().navigationTitle("Dashboard"),
                        tag: NavigationItem.sel1,
                        selection: $selection
                ) {
                    Label("Dashboard", systemImage: "globe")
                }.tag(NavigationItem.sel1)
                NavigationLink(
                        destination: ViewRepresentable(title: "TestView").navigationTitle("TestView"),
                        tag: NavigationItem.sel2,
                        selection: $selection
                ) {
                    Label("Dashboard", systemImage: "globe")
                }.tag(NavigationItem.sel2)
            }
                .padding(.top, 16)
                .navigationTitle("SomeApp")
                .listStyle(SidebarListStyle())
        }.frame(minWidth: 1000, idealWidth: 1200, maxWidth: .infinity, minHeight: 600, idealHeight: 800, maxHeight: .infinity, alignment: .center)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

标签: macosswiftuiswiftui-listswiftui-navigationlink

解决方案


推荐阅读