I have a collection view with a reusable cell. That cell has a background, label and button. I can reference which background is in each cell. I would like to update the text in the label when the button is pressed based on which background that cell has. I am having trouble referencing the cell. let cell = collectionView.cellForItem(at: indexPath) gives me an error. How do I reference this cell?
I am ok if the label gets reset when the user scrolls the collection view.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MyColectionCell
cell.CellBG.image = UIImage(named: ButtonBGs[indexPath.row])
cell.CellBG.layer.cornerRadius=10
cell.layer.shadowColor = UIColor.black.cgColor
cell.layer.shadowOffset = CGSize(width: 1, height: 10)
cell.layer.shadowOpacity = 0.3
cell.layer.shadowRadius = 10
cell.layer.masksToBounds = false
cell.Info.tag = indexPath.row
cell.Info.addTarget(self, action: #selector(Info), for: .touchUpInside)
cell.CellText.text = " "
cell.CellText.tag = indexPath.row
return cell
}
@objc func Info(sender: UIButton){
let indexPath = IndexPath(row: sender.tag, section: 0)
let cell = collectionView.cellForItem(at: indexPath) //gives me error "Reference to member 'cellForItem' cannot be resolved without a contextual type"
if((ButtonBGs[indexPath.row])=="bt-tower"){
cell.CellText.text = "New Text"
}
}
CodePudding user response:
I would recommend a different approach to this. The code you provided indicates all of this could be performed in the cell itself.
Give it a property of type String
that holds the imagename, assign it inside of func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath:
and perform the button action/comparison inside the Button @IBAction
.
Also, that code manipulating the layer should also be in the cell itself. The cellForItemAt indexpath:
function should only provide the data the cell presents.
CodePudding user response:
I figured it out with some help. I am using an array for the label text and keeping the labels alpha at 0. When I need to display it I change the alpha and reload the data self.myCollection.reloadItems(at: [indexPath]) This way only the text for the indexed cell is shown.