首页 > 解决方案 > Swift - 想要在单击集合视图单元格内的按钮时进行更改

问题描述

我创建了一个包含 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
    }
}

谢谢 !

标签: iosxcodeswift3

解决方案


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

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

推荐阅读