SwiftUI:解决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
相关产品推荐
相关产品推荐

