繁体   English   中英

如何在单击时更改collectionviewcell或按钮的渐变?

[英]How do I change the gradient of a collectionviewcell or button on click?

我在UIViews上使用了这样的渐变:

//the cells gradient colors
    cellgradient.frame = cell.imageView.bounds
    cellgradient.cornerRadius = cellgradient.frame.height / 2
    cellgradient.colors = [UIColor(hexString: "#ef473a")!, UIColor(hexString: "#cb2d3e")!].map { $0.cgColor }
    cellgradient.startPoint = CGPoint(x: 0.0, y: 0.5)
    cellgradient.endPoint = CGPoint(x: 1.0, y: 0.5)
    cellgradient.colors = [UIColor(hexString: "#ef473a")!, UIColor(hexString: "#cb2d3e")!]
    cell.imageView.layer.insertSublayer(cellgradient, at: 0)

现在,当我选择单元格或取消选择该单元格时,我想更改当前渐变。 我该怎么做呢?

编辑

根据答案,我做了以下工作:

class CollectionViewCell : UICollectionViewCell
{

@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var imageView: UIImageView!
public var checked = false
public var animated = false
public var cellgradient: CAGradientLayer = CAGradientLayer()

override var bounds : CGRect {
    didSet {
        self.layoutIfNeeded()
    }
}

override var isSelected: Bool {
    didSet {
        if isSelected {
            cellgradient.colors = [UIColor(hexString: "#ef473a")!, UIColor(hexString: "#cb2d3e")!].map { $0.cgColor }
        } else {
            cellgradient.colors = [UIColor(hexString: "#29a1e2")! , UIColor(hexString: "#485ac8")!].map { $0.cgColor }
        }
    }
}
func addthegradientLayer() {

    //the cells gradient colors
    cellgradient.frame = imageView.bounds
    cellgradient.cornerRadius = cellgradient.frame.height / 2
    cellgradient.colors = cellgradient.colors = [UIColor(hexString: "#29a1e2")! , UIColor(hexString: "#485ac8")!].map { $0.cgColor }
    cellgradient.startPoint = CGPoint(x: 0.0, y: 0.5)
    cellgradient.endPoint = CGPoint(x: 1.0, y: 0.5)
    imageView.layer.insertSublayer(cellgradient, at: 0)
}

而且有效。 现在我只剩下一个问题:单元格的图像视图隐藏在渐变后面。 我该如何解决?

我可以通过子类化UICollectionViewCell 您的自定义单元格类可以具有引用其渐变层的属性。

在单元格的初始化程序中,像现在一样将渐变层添加到图像视图中。 然后,覆盖isSelected属性的didSet并为选定状态或正常状态修改渐变层。

didSet {}中的isSelected和!isSelecet的颜色十六进制字符串相同。

如果可以将图层插入当前插座的下方或之后

imageView.layer.insertSublayer(cellgradient, below: nameLabel.layer)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM