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

点击CollectionView Cell跳转ViewController并传值及代理使用问题

解决CollectionView点击Cell跳转并传值的问题

步骤1:设置CollectionView的Delegate并遵守协议

首先在你的ViewController类声明中添加UICollectionViewDelegate协议:

class YourViewController: UIViewController, UICollectionViewDelegate {
    // 你的现有代码
}

然后在setupCollectionView方法里,给collectionView绑定delegate:

private func setupCollectionView() {
    // 现有布局、约束、Cell注册等代码...
    
    collectionView.delegate = self // 新增这行
    
    setupViewModel()
}

步骤2:实现点击Cell的代理方法

添加collectionView(_:didSelectItemAt:)方法,处理跳转和传值逻辑:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    // 1. 获取选中Cell对应的数据源对象
    guard let selectedPokemon = dataSource.itemIdentifier(for: indexPath) else { return }
    
    // 2. 提取需要传递的URL(可根据需求做格式校验)
    guard let targetUrl = URL(string: selectedPokemon.url) else {
        print("URL格式错误")
        return
    }
    
    // 3. 初始化目标ViewController并传递参数
    let detailVC = YourDetailViewController() // 替换为你的第二个VC类名
    detailVC.targetUrl = targetUrl // 假设第二个VC有接收URL的属性
    
    // 4. 执行跳转(根据项目结构选择push或present)
    navigationController?.pushViewController(detailVC, animated: true)
    // 若无导航控制器则用present:present(detailVC, animated: true)
}

小优化:修正ViewModel的Snapshot更新逻辑

你当前setupViewModel中用reloadData()刷新列表,不符合Diffable DataSource的最佳实践,建议改成增量更新Snapshot:

private func setupViewModel() {
    pokedexListVM.$pokemons
        .receive(on: RunLoop.main)
        .sink(receiveValue: { [weak self] pokemons in
            guard let self = self else { return }
            var snapshot = NSDiffableDataSourceSnapshot<Section, PokemonResults>()
            snapshot.appendSections([.main])
            snapshot.appendItems(pokemons, toSection: .main)
            self.dataSource.apply(snapshot, animatingDifferences: true)
        }).store(in: &subscriptions)
}

这种方式会自动处理列表的局部更新,比全量刷新更高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 19:10:47