当自定义collectionViewCell中包含标签时,不会调用didSelectItemAtIndexPath

时间:2016-08-10 06:24:23

标签: ios swift uicollectionview uicollectionviewcell

我有一个自定义collectionViewCell,其标签覆盖整个collectionViewCell大小。一切似乎按计划工作,但唯一似乎不起作用的是collectionViewCell不调用didSelectItemAtIndexPath。我做错了什么?为什么UILabel没有将事件传递给superview。在UILabel上启用了用户交互。

编辑:将标签添加到标签

  func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    collectionView.registerNib(UINib(nibName: "ProductSizeCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "CollectionViewCell")
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as! ProductSizeCollectionViewCell
    let tap = UITapGestureRecognizer()
    tap.addTarget(self, action: #selector(ProductDetailPageController.sizeTapped(_:)))
    cell.sizeLabel.tag = indexPath.row
    cell.sizeLabel.addGestureRecognizer(tap)
    return cell
 }


func sizeTapped(sender : UITapGestureRecognizer) {
    let view  = sender.view as? UILabel
    print(view!.tag)
    let indexPath = NSIndexPath(forItem: view!.tag, inSection: 0)
    let cell = collectionViewSize.cellForItemAtIndexPath(indexPath) as! ProductSizeCollectionViewCell
    if !cell.selectedCell {
        cell.selectedCell = true
        cell.layer.borderColor = UIColor(hexString: "9E9E9E").CGColor
    } else {
        cell.selectedCell = false
        cell.layer.borderColor = UIColor(hexString: "E8E6E4").CGColor
    }
    collectionViewSize.reloadData()
}

1 个答案:

答案 0 :(得分:0)

可能你在其他地方遇到问题。您可以通过在控制台上登录来仔细检查集合视图委托是否真的设置了吗?

此外:

collectionView.registerNib(UINib(nibName: "ProductSizeCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "CollectionViewCell")

应该在一些设置方法中设置一次。

因为集合视图(如表格视图)使用可重复使用的单元格这一行:

cell.sizeLabel.addGestureRecognizer(tap)

可以为一个标签添加多个手势识别器。在那种情况下,我更喜欢由单元格触发的回调块。

相关问题