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

Swift使用UISearchBar过滤UICollectionView后点击cell跳转数据错误如何解决

问题原因

跳转逻辑的数据源没有和列表展示逻辑对齐:列表在搜索激活状态下展示filtered数组的内容,但跳转时始终从全量数据源resources中取对应索引的资源,导致索引不匹配。

修复方案

修改prepare(for:sender:)方法中资源取值的逻辑,和列表展示保持一致,区分搜索状态选择数据源:

extension resViewViewController {
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "si_viewResToPost", let vc = segue.destination as? resPostViewController {
            vc.delegate = self
        } else if segue.identifier == "si_resourceListToDetail",
                  let vc = segue.destination as? detailedResViewController, let indexPath = sender as? IndexPath {
            // 区分搜索状态选择对应数据源
            let selectedResource = searchActive ? filtered[indexPath.row] : resources[indexPath.row]
            vc.resource = selectedResource
        }
    }
}

可选优化点

  • 目前搜索逻辑中如果用户清空搜索框,filtered数组为空,searchActive会被设为false,逻辑正常;如果需要优化空搜索结果的提示,可以自行补充空状态视图。
  • loadResources方法中现在每解析一条数据就调用一次collection.reloadData(),可以修改为所有数据解析完成后统一调用一次,减少不必要的UI刷新。
  • 你遵守的UISearchDisplayDelegate是iOS 8就废弃的协议,不需要再声明遵守,可以直接删掉,避免编译警告。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 17:06:08