从 UITapGestureRecognizer 访问子视图

Accessing subviews from UITapGestureRecognizer

我有一个集合视图,其中包含基于数组填充的单元格。每个单元格都有一个 UIImageView 和一个 UILabel。每次点击 Cell View 本身时,我都希望能够更新 UILabel 中的文本。我的点击手势工作正常,我可以打印出发件人信息并访问发件人视图,甚至获得恢复标识符,但我似乎无法访问其中的 'myImage' 或 'myLabel' 子视图被窃听的细胞。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! CardCell

    cell.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tap)))

    let railroadName = railroadNames[indexPath.item]
    cell.myImage.image = #imageLiteral(resourceName:railroadName)
    cell.myImage.clipsToBounds = true
    cell.myImage.layer.cornerRadius = 8
    cell.restorationIdentifier = railroadName

    cell.myLabel.isHidden = true
    cell.myLabel.text = "2"
    cell.myLabel.layer.backgroundColor = UIColor(red:0.25, green:0.52, blue:0.96, alpha:1.0).cgColor
    cell.myLabel.layer.cornerRadius = 18
    cell.myLabel.textColor = UIColor.white

    return cell
}

@objc func tap(_ sender: UITapGestureRecognizer) {
    //print(sender)
    //print(sender.view?.restorationIdentifier)
}

无法访问子视图。想要从 'myLabel' 中获取当前文本并在每次点击时将计数增加 1。

您可以使用以下代码获取单元格的标签文本。但我坚持要你在 railroadNames 数组中管理它。因此,您可以将标签文本保存在数组对象的字段中,并可以使用下面的代码使用索引路径获取该字段值,并根据您的要求执行操作。然后您可以重新加载该特定单元格以在 tableview 上显示效果。

此外,您应该使用 didSelectItemAt 方法来获取 select 单元格事件。如果没有必要,请使用 UITapGestureRecognizer.

@objc func tap(_ sender: UITapGestureRecognizer) {

    //Get Collection view cell indexpath on based of location of tap gesture
    let cellPosition = sender.location(in: self.collectionView)
    guard let indexPath = self.collectionView.indexPathForItem(at: cellPosition) else{
        print("Indexpath not found")
        return
    }

    //Get Ceollection view cell
    guard let cell = self.collectionView.cellForItem(at: indexPath) as? CellMainCategoryList else{
        print("Could't found cell")
        return
    }

    //Get String of label of collection view cell
    let strMyLable = cell. myLabel.text
    //you can process addition on based of your requirement here by getting Int from above string.
}

除了上面的代码,您还可以像下面的代码一样管理它:

@objc func tap(_ sender: UITapGestureRecognizer) {

    let cellPosition = sender.location(in: self.collectionViewCategaries)
    guard let indexPath = self.collectionViewCategaries.indexPathForItem(at: cellPosition) else{
        print("Indexpath not found")
        return
    }
    let railroadName = railroadNames[indexPath.item]
    let myLableText = railroadName.myLabelValue
    //update value
    railroadName.myLabelValue = "2"

    self.collectionView.reloadItems(at: [indexPath])
}

希望对您有所帮助。