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

如何在UICollectionView完成多选操作后展示UIAlertController

实现方案

步骤1:开启UICollectionView多选配置

首先你需要先开启集合视图的多选支持,在viewDidLoad或者CollectionView初始化的位置添加如下代码:

collectionView.allowsMultipleSelection = true

如果你需要保留同section单选、跨section可多选的原有逻辑,你原来的shouldSelectItemAt代理方法不需要修改;如果需要支持同section内多选,删除该方法内遍历取消同section选中项的代码即可。

步骤2:定义多选完成的触发时机

多选完成的触发逻辑通常有两种实现方式,你可以根据业务需求选择:

方案A:用户点击完成按钮触发(推荐)

这种方式给用户自主调整选择的空间,适配绝大多数多选场景:

  1. 先添加完成按钮入口,在viewDidLoad中添加:
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "完成", style: .done, target: self, action: #selector(finishSelection))
  1. 实现完成按钮点击逻辑,获取选中内容并弹提示:
@objc private func finishSelection() {
    guard let selectedIndexPaths = collectionView.indexPathsForSelectedItems, 
          !selectedIndexPaths.isEmpty else {
        // 未选中任何项时的提示
        let emptyAlert = UIAlertController(title: "提示", message: "请至少选择一项", preferredStyle: .alert)
        emptyAlert.addAction(UIAlertAction(title: "知道了", style: .default))
        present(emptyAlert, animated: true)
        return
    }
    
    // 提取所有选中的内容
    let selectedItems = selectedIndexPaths.map { indexPath in
        shiftSection[indexPath.section].options[indexPath.row]
    }
    
    // 弹出选择完成提示
    let alert = UIAlertController(title: "选择完成", message: "你共选中了\(selectedItems.count)项", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "取消", style: .cancel))
    alert.addAction(UIAlertAction(title: "确认", style: .default, handler: { _ in
        // 此处填写确认选中后的业务逻辑
    }))
    present(alert, animated: true)
}

方案B:选中指定数量后自动触发

如果你的业务有明确的选中数量要求,可以在选中代理中判断数量自动弹提示:
在didSelectItemAt代理方法中添加判断逻辑:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let model = shiftSection[indexPath.section].options[indexPath.row]
    print(model.title)
    
    // 示例:选满2项自动弹出提示
    guard let selectedCount = collectionView.indexPathsForSelectedItems?.count, 
          selectedCount == 2 else {
        return
    }
    // 调用上述的提示弹窗逻辑即可
    finishSelection()
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 17:06:00