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

SwiftUI中contextMenu手动修改List选中项后返回行数异常

List批量选中后contextMenu识别行数异常问题

问题描述

在给SwiftUI的List添加contextMenu(forSelectionType:menu:primaryAction:)时出现以下异常:

  • 启用编辑模式手动点击选中行,contextMenu能正确返回所有选中的行数
  • 通过按钮直接修改selection集合(比如点击全选按钮),contextMenu返回的选中行数不正确,仅能识别当前已渲染的单元格
  • 全选后滚动列表至底部,contextMenu返回的行数会恢复正确,说明只有已渲染的单元格才会被contextMenu识别

复现代码

struct ContentView: View {
    let rows = (0..<100).map{ "Row: \($0)" }
    @State var selection: Set<String> = []

    var body: some View {
        List(selection: $selection) {
            ForEach(rows, id: \.self) { row in
                Text(row).tag(row)
            }
        }
        .contextMenu(forSelectionType: String.self) { contextMenuRows in
            Button("Number of rows in the contextMenu: \(contextMenuRows.count)") {}
        }
        .toolbar {
            ToolbarItem(placement: .navigationBarLeading) {
                if selection.isEmpty {
                    Button("Select All") { selection = Set(rows) }
                } else {
                    Button("Deselect All") { selection = [] }
                }
            }

            ToolbarItem(placement: .navigationBarTrailing) {
                EditButton()
            }
        }
    }
}

注意:需将ContentView嵌入NavigationView中才能显示导航栏

现象总结

  • 手动逐行选中时,contextMenu功能正常,能正确统计选中行数
  • 点击全选按钮后,contextMenu仅显示前9行(当前可见的已渲染单元格数量)
  • 滚动列表至底部后,所有选中行都能被contextMenu识别

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 08:40:31