Swift中如何在HomeVC内给xib自定义CollectionViewCell的按钮添加点击事件
问题说明
自定义UICollectionViewCell的XIB文件和HomeVC所在的Storyboard/ViewController XIB属于独立的资源文件,Interface Builder不支持跨不同资源文件做@IBAction的直接拖拽连线,所以你之前的直接拖拽操作无法生效。
实现方案
方案1:低修改成本的target-action绑定(直接复用你已有的@IBAction)
@IBAction本质只是暴露给Interface Builder识别的方法,完全可以直接作为addTarget的参数绑定,不需要修改你已经写好的@IBAction代码:
- 在
cellForItemAtIndexPath代理方法中添加绑定逻辑:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MainCollectionViewCell", forIndexPath: indexPath) as! MainCollectionViewCell cell.arrivingLabel.text = indexData.arriv cell.lblDiscountedPrice.text = indexData.discPrice // 新增绑定逻辑,直接指向你写好的@IBAction cell.btnDetails.addTarget(self, action: #selector(productDetailsMain(_:)), for: .touchUpInside) return cell }
- 你已经定义的
@IBAction可以直接正常触发,如需获取当前点击对应的行数据可以按如下方式实现:
@IBAction func productDetailsMain(_ sender: UIButton){ // 通过按钮位置获取对应的indexPath let point = sender.convert(.zero, to: collectionView) guard let indexPath = collectionView.indexPathForItem(at: point) else { return } let currentRowData = yourDataSourceArray[indexPath.row] // 后续业务逻辑 }
方案2:闭包回调(更符合Swift编码规范)
如果希望代码逻辑更清晰、避免target-action可能出现的循环引用问题,可以用闭包实现回调:
- 在
MainCollectionViewCell类中定义闭包属性,同时绑定cell内按钮的点击事件:
class MainCollectionViewCell: UICollectionViewCell { @IBOutlet weak var arrivingLabel: UILabel! @IBOutlet weak var lblDiscountedPrice: UILabel! @IBOutlet weak var btnDetails: UIButton! // 定义按钮点击回调闭包 var onDetailsButtonTap: (() -> Void)? // 把cell内btnDetails的点击事件连线到这个方法(在cell自身的XIB中操作即可) @IBAction func detailsButtonTapped(_ sender: UIButton) { onDetailsButtonTap?() } }
- 在HomeVC的
cellForItemAtIndexPath中处理回调:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MainCollectionViewCell", forIndexPath: indexPath) as! MainCollectionViewCell cell.arrivingLabel.text = indexData.arriv cell.lblDiscountedPrice.text = indexData.discPrice // 处理点击回调 cell.onDetailsButtonTap = { [weak self] in guard let self = self else { return } self.productDetailsMain(sender: cell.btnDetails) } return cell }
内容的提问来源于stack exchange,提问作者Swift
相关产品推荐
相关产品推荐

