SwiftUI:摆脱 SelectionManagerBox<String> 尝试每帧更新多次

问题描述 投票:0回答:1

我花了几个小时试图摆脱我的应用程序上的错误消息:

List with selection: SelectionManagerBox<String> tried to update multiple times per frame.

这是一款 macOS 14 应用程序。由于我无法找到解决方案,因此我决定尝试创建一个最小的可重现示例。这是这个例子:

import SwiftUI

struct ContentView: View {
    @State var selection: String = ""
    @State var secondSelection: String = ""
    
    var body: some View {
        NavigationSplitView {
            List(selection: $selection) {
                NavigationLink("A", value: "A")
                NavigationLink("B", value: "B")
                NavigationLink("C", value: "C")
            }
        } content: {
            List(selection: $secondSelection) {
                NavigationLink("1", value: "1")
                NavigationLink("2", value: "2")
                NavigationLink("3", value: "3")
            }
        } detail: {
            Text("\(selection) - \(secondSelection)")
        }
    }
}

#Preview {
    ContentView()
}

这个例子真的很简单,我想我们什么也做不了吧? 谢谢!

我在我的应用程序上尝试了所有方法,但问题似乎与 SwiftUI 和 NavigationSplitView 有关……

swift swiftui navigation
1个回答
0
投票

当我使用

onAppear
自动选择第一个导航项时,我收到了相同的消息。我还对选定的导航项使用了可选选项。

添加非常短的睡眠时间就消除了该消息(目前的解决方法):

enum NavItem: String, Hashable {
    case home
    case buy
}

struct MyView: View {
    @State private var selectedNavItem: NavItem?

    var body: some View {
        NavigationSplitView() {
            List(selection: $selectedNavItem) {
                NavigationLink(value: NavItem.home) { homeLabel }
                NavigationLink(value: NavItem.buy) { buyLabel }
            }
        } detail: {
            switch selectedNavItem {
                case .some(.home):
                    HomeView()
                case .some(.buy):
                    BuyView()
                case .none:
                    Text("")
            }
        }
        .onAppear {
            Task { @MainActor in
                try await Task.sleep(for: .seconds(0.05))
                selectedNavItem = .home
            }
        }
    }

    private var homeLabel: some View { ... }
    private var buyLabel: some View { ... }
}
© www.soinside.com 2019 - 2024. All rights reserved.