[英]gradient keeps switching between cells in collection view in swift
我的收藏夾視圖單元格具有漸變背景,並且每個漸變都取決於該單元格的標記(例如,聖誕節是紫色漸變,生日是綠色漸變),但是在收藏夾視圖中滾動時,漸變會不斷變化。 有辦法解決這個問題嗎?
這是我用來將漸變設置為背景視圖的代碼。 它在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()
讀取代碼,您總是會初始化一個新的CAGradientLayer
並將其插入到單元格中的最低位置。 每次再次調用setGradientBackground()
時,新的漸變層將位於您已插入的所有其他漸變下面。
嘗試從子層獲取已經存在的CAGradientLayer
並設置新顏色。
var gradientLayer = CAGradientLayer()
if let sublayers = layer.sublayers {
for sublayer in sublayers {
if let gLayer = sublayer as? CAGradientLayer {
gradientLayer = gLayer
break
}
}
}
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)
編輯
這是使用像版本更迅速(SWIFT 4.2) compactMap()
用於獲取在所述第一現有的梯度層layer.sublayers
:
if let existingLayer = (layer.sublayers?.compactMap { $0 as? CAGradientLayer })?.first {
gradientLayer = existingLayer
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.