Swift使用Protocol获取UITableViewCell内嵌UICollectionView的cell索引
问题根源
你当前的写法存在两个核心问题:
- 自定义代理回调只返回了外层UITableViewCell,没有把点击的UICollectionViewCell对应的索引传递出来
- 你在ViewController的回调方法里错误使用了UITableView的行号作为附件数组的索引,而你的UITableView当前只有1行,所以行号永远是0,必然永远拿到第一个附件的数值。
修复步骤
1. 修改代理协议,新增索引参数
修改CustomCellDelegate的回调方法,增加选中的collectionView索引参数:
protocol CustomCellDelegate: class { // 新增selectedIndex参数,返回点击的collectionView cell位置 func sharePressed(cell: ProposalTableVIewCell, selectedIndex: Int) }
2. 触发回调时传递按钮的tag值
你已经给按钮的tag赋值了对应的collectionView索引,在触发代理时把这个tag传出去即可:
@objc func connected(sender: UIButton){ // 把sender.tag作为选中索引传给代理 delegate?.sharePressed(cell: self, selectedIndex: sender.tag) }
3. 修改ViewController的回调实现,用传过来的索引取值
不要用UITableView的行号作为附件数组的索引,直接用回调返回的selectedIndex取值:
func sharePressed(cell: ProposalTableVIewCell, selectedIndex: Int) { // 直接用回调返回的collection索引取对应附件 let name = getBitDetails?.result?.bid?.get_attachments?[selectedIndex].filename // 后续处理逻辑 }
可选优化
如果后续你的UICollectionView改成多Section布局,用tag存item会有冲突风险,可以用坐标转换的方式拿到准确的IndexPath:
@objc func connected(sender: UIButton){ let buttonPosition = sender.convert(CGPoint.zero, to: self.attetchmentsCollectionview) if let indexPath = self.attetchmentsCollectionview.indexPathForItem(at: buttonPosition) { delegate?.sharePressed(cell: self, selectedIndex: indexPath.item) } }
内容的提问来源于stack exchange,提问作者Swift
相关产品推荐
相关产品推荐

