【发布时间】:2018-12-03 15:25:46
【问题描述】:
我的收藏视图单元格有一个渐变背景,每个渐变都不同,具体取决于单元格的标签(例如圣诞节是紫色渐变,生日是绿色渐变)但是当滚动浏览收藏视图时,渐变会保持关于改变细胞。有没有办法解决这个问题?
这是我用来将渐变设置为背景视图的代码。它在cellForItemAt
cell.mainView.setGradientBackground(colours: self.getColourFromTag(tag: self.lists[indexPath.item].tag))
.setGradientBackground 是 UIView 的扩展,它只是为背景设置渐变。此处显示:
func setGradientBackground(colours: [CGColor]) {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = bounds
gradientLayer.colors = colours
gradientLayer.locations = [0.0, 1.0]
gradientLayer.startPoint = CGPoint(x: 1.0, y: 1.0)
gradientLayer.endPoint = CGPoint(x: 0.0, y: 0.0)
layer.insertSublayer(gradientLayer, at: 0)
}
我使用下面的方法来获取渐变中的颜色
func getColourFromTag(tag: String) -> [CGColor] {
if tag == "Christmas" {
return [Colours.gradients.festive.start.cgColor, Colours.gradients.festive.end.cgColor]
}else if tag == "Birthday" {
return [Colours.gradients.lime.start.cgColor, Colours.gradients.lime.end.cgColor]
}else if tag == "Valentines Day" {
return [Colours.gradients.strawberry.start.cgColor, Colours.gradients.strawberry.end.cgColor]
}else if tag == "Charity" {
return [Colours.gradients.blueberry.start.cgColor, Colours.gradients.blueberry.end.cgColor]
}else if tag == "Event" {
return [Colours.gradients.fire.start.cgColor, Colours.gradients.fire.end.cgColor]
}else{
return [Colours.gradients.midnight.start.cgColor, Colours.gradients.midnight.end.cgColor]
}
}
我尝试将每个 [color] 附加到一个数组中,然后将其放入 .setGradientBackground 的 indexPath.item 中,如下所示:
var colours = [[CGColor]]()
colours[indexPath.item] = self.getColourFromTag(tag: self.lists[indexPath.item].tag)
cell.mainView.setGradientBackground(colours: colours[indexPath.item])
但是,这不起作用,因为它超出了范围。有没有人有办法解决吗?谢谢。
【问题讨论】:
-
setGradientBackground()是什么意思? -
我已编辑问题以显示该代码:)
-
细胞被重复使用,你每次都这样做
layer.insertSublayer(gradientLayer, at: 0)。因此,通过重用,如果单元格有前一层,它将是:0 处的层:新渐变,1 处的层:前一层等。如果发现为CAGradientLayer,则删除前一层 -
感谢您的回复,我该怎么做呢? (如果找到则删除图层)
-
layer.sublayers.filter(where: {$0 as? CAGradient}).forEach{$0.removeFromSuperlayer}?
标签: ios swift uicollectionview gradient