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

Mac平台NavigationSplitView用searchSuggestions出现AttributeGraph循环报错

解决Mac平台NavigationSplitView使用searchSuggestions时的AttributeGraph循环错误

问题背景

在Mac平台使用NavigationSplitView搭配searchable和searchSuggestions修饰符时,控制台会输出AttributeGraph: cycle detected through attribute错误,移除searchSuggestions后功能恢复正常。通过AG: print_cycles()符号断点排查,确认问题源于搜索建议弹窗与NSWindow争抢第一响应者,触发了SwiftUI内部的响应者链循环冲突。

修复方案

核心思路是避免直接在searchSuggestions闭包中返回静态视图,改用动态数据源驱动建议内容,同时优化列表过滤逻辑:

修改后的代码

struct ContentView: View {
    let platforms: [String] = ["Test1", "Test2", "Test3", "Test4"]
    
    @State var selection: String = ""
    @State var searchText: String = ""
    @State private var searchSuggestions: [String] = ["test123"]
    
    var body: some View {
        NavigationSplitView {
            List(selection: $selection) {
                // 提前过滤数组,避免在ForEach内嵌入条件判断
                ForEach(filteredPlatforms, id: \.self) { platform in
                    Text(platform).tag(platform)
                }
            }
        } detail: {
            Text(selection.isEmpty ? "Make a selection" : selection)
        }
        .searchable(text: $searchText, placement: .sidebar)
        .searchSuggestions {
            // 用ForEach包裹建议项,让SwiftUI以动态方式处理视图生命周期
            ForEach(searchSuggestions, id: \.self) { suggestion in
                Text(suggestion).searchCompletion(suggestion)
            }
        }
    }
    
    // 提取过滤逻辑为计算属性,提升代码可读性与维护性
    private var filteredPlatforms: [String] {
        searchText.isEmpty ? platforms : platforms.filter { $0.contains(searchText) }
    }
}

其他可行思路

  • 调整searchable的placement参数,尝试使用默认值(不指定.sidebar),部分场景下可避开响应者链冲突
  • 通过onChange(of: searchText)动态更新searchSuggestions数组,根据搜索文本生成匹配的建议内容,进一步降低静态视图引发的循环风险

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 21:12:40