Swift - 想要在单击集合视图单元格内的按钮时进行更改

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

我创建了一个包含 UIView 的集合视图单元格,在 UIView 内部,有一个按钮。 我想要做的是当单击按钮时它会更改 UIView 边框颜色。 我从服务器加载数据并将其显示到集合视图。

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
    }
}

谢谢!

您可以将按钮点转换为视点并获得所需的单元格。

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()
    }
}