从UITapGestureRecognizer访问子视图

时间:2019-01-13 09:24:16

标签: ios swift uitapgesturerecognizer

我有一个包含基于数组填充的单元格的集合视图。每个单元都有一个UIImageView和一个UILabel。我希望每次点击“单元格视图”本身时都能够更新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。

1 个答案:

答案 0 :(得分:2)

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

此外,您应该使用didSelectItemAt方法来获取选择单元格事件。如有必要,请使用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])
}

希望这会有所帮助。