You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI:解决NavigationSplitView中SelectionManagerBox帧重复更新错误

解决macOS 14中NavigationSplitView多列表选择的“SelectionManagerBox多次更新”错误

在macOS 14应用中使用NavigationSplitView嵌套两个带选择绑定的List时,会触发以下错误:

List with selection: SelectionManagerBox tried to update multiple times per frame

问题复现代码

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

修复方案

将选择绑定的类型改为可选字符串(String?),并将初始值设为nil,避免空字符串触发不必要的状态更新:

import SwiftUI

struct ContentView: View {
    @State var selection: String? = nil
    @State var secondSelection: String? = nil
    
    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()
}

原因说明

这个错误是macOS 14 SwiftUI的已知问题:当List的selection绑定到非可选类型且初始值为空字符串时,NavigationSplitView会在布局过程中触发SelectionManager的重复更新。使用可选类型并将初始值设为nil,可以避免SwiftUI将空字符串视为有效选择值,从而消除重复更新的触发条件。

内容的提问来源于stack exchange,提问作者TheJof

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 08:17:23