>我有一个集合视图,其中包含基于数组填充的单元格。每个单元格都有一个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 次。
您可以使用以下代码获取单元格的标签文本。 但我坚持要在 railroadNames 数组中管理它。 因此,您可以将标签文本保存在数组对象的字段中,并可以使用以下代码使用 indexpath 获取该字段值,并根据您的要求执行操作。 然后,您可以重新加载该特定单元格以显示对表视图的影响。
此外,您应该使用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])
}
希望这有帮助。