如何在点击时更改集合视图单元或按钮的渐变?

时间:2017-10-23 19:44:41

标签: ios swift colors cell gradient

我在我的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)
}

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

3 个答案:

答案 0 :(得分:0)

我会通过subclassing UICollectionViewCell执行此操作。您的自定义单元格类可以具有引用其渐变图层的属性。

在单元格的初始值设定项中,像现在一样将渐变图层添加到图像视图中。 Then, override the isSelected property's didSet并修改选定或正常状态的渐变图层。

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

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