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

NavigationSplitView删除侧边栏项后选择其他项崩溃问题求助

问题现象

使用NavigationSplitView时,删除侧边栏中的某个项目后,选择其他侧边栏项(如"All")会触发崩溃,错误信息为:Thread 1: EXC_BREAKPOINT (code=1, subcode=0x1c44d488c)。无论使用普通String还是Core Data对象都会出现该问题。

重现步骤

  • 启动应用,点击"Add"按钮新增一个侧边栏项目
  • 在侧边栏中选中新增的项目
  • 在详情视图中点击"Delete"按钮删除该项目
  • 再次在侧边栏中选择"All"选项,应用崩溃

问题原因

这是SwiftUI NavigationSplitView的状态同步bug:当删除当前选中的列表项后,虽然手动将selection设置为nil,但List组件内部的选中状态与NavigationSplitView的全局状态并未完全同步,导致后续选择其他有效选项时,框架内部出现状态冲突,触发断点崩溃。

修复方案

删除项目后,不要将selection设置为nil,而是直接切换到一个存在的有效选项(比如示例中的.all),确保List和NavigationSplitView的状态始终保持一致,避免状态冲突。

修改删除按钮的代码逻辑:

Button(role: .destructive) {
    if let index = strings.firstIndex(of: string) {
        strings.remove(at: index)
        // 将selection切换到存在的.all选项,而非设置为nil
        self.selectionString = .all
    }
} label: {
    Text("Delete")
}

完整修复代码

import SwiftUI

@main
struct FB_SwiftUI_NavigationSplitView_Delete_SelectApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

enum SelectionString: Hashable {
    case all
    case item(String)
}

struct ContentView: View {
    @State private var selectionString: SelectionString?
    @State private var strings: [String] = []

    var body: some View {
        NavigationSplitView {
            List(selection: $selectionString) {
                Section {
                    NavigationLink(value: SelectionString.all) {
                        Text("All")
                    }
                }
            
                Section {
                    ForEach(strings.sorted(), id: \.self) { string in
                        NavigationLink(value: SelectionString.item(string)) {
                            Text(string)
                        }
                    }
                }
            }
            .toolbar {
                ToolbarItem {
                    Button("Add") {
                        strings.append(UUID().uuidString)
                    }
                }
            }
        } detail: {
            if let selectionString {
                switch selectionString {
                case .all:
                    Text("All")
                
                case .item(let string):
                    Button(role: .destructive) {
                        if let index = strings.firstIndex(of: string) {
                            strings.remove(at: index)
                            // 修复:切换到存在的选项而非设置为nil
                            self.selectionString = .all
                        }
                    } label: {
                        Text("Delete")
                    }
                }
            } else {
                Text("Select an item")
            }
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 04:50:16