Calvin Ng
Calvin Ng

Reputation: 3

Swift - want to make changes when a button clicked which is inside a collection view cell

I have created a collection view cell which include a UIView and inside the UIView, there is a button. What I'm trying to do is when the button clicked it will change the UIView border color. And I load data from server and display it to the collection view.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CypherCollectionViewCell", for: indexPath as IndexPath) as! CypherCollectionViewCell

    cell.tickButton.addTarget(self, action: #selector(tickButtonClicked(sender:)), for: .touchUpInside)

    return cell
}

@objc func tickButtonClicked( sender: UIButton) {
    if sender.isSelected {
        sender.isSelected = false
        // To change the UIView border color
    } else {
       sender.isSelected = true
       // To change the UIView border color
    }
}

Thank you !

Upvotes: 0

Views: 1152

Answers (1)

sinner
sinner

Reputation: 513

You can convert the button points into viewpoints and get the desired cell.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CypherCollectionViewCell", for: indexPath as IndexPath) as! CypherCollectionViewCell

    cell.tickButton.addTarget(self, action: #selector(tickButtonClicked(sender:)), for: .touchUpInside)

    return cell
}

@objc func tickButtonClicked( sender: UIButton) {

    var convertedPoint : CGPoint = sender.convert(CGPoint.zero, to: self. collectionView)
    var indexPath = self. collectionView.indexPathForItemAtPoint(convertedPoint)
    let cell = self. collectionView.cellForItemAtIndexPath(indexPath) as! CypherCollectionViewCell

    if sender.isSelected {
        sender.isSelected = false
        // To change the UIView border color
        cell.view.borderColor = UIColor.blue()
    } else {
       sender.isSelected = true
       // To change the UIView border color
        cell.view.borderColor = UIColor.red()
    }
}

Upvotes: 1

Related Questions