【发布时间】:2017-06-16 08:35:45
【问题描述】:
我有一个带有渐变子视图的UICollectionViewCell。
在我的视图控制器中,我有排序 CoreData 的按钮,然后是 UICollectionView 上的 reloadData()。
为了避免我的渐变子视图被一次又一次地绘制(就像过去发生的那样),我在prepareForReuse() 中实现了removeFromSuperview()。
在那里,我还实现了一个跟踪渐变存在的标志,因此在加载单元格时我仍然添加一个新的渐变。
但是删除渐变后,我的willMove(toSuperview: ) 不起作用,渐变视图也不会出现。
我的逻辑有什么问题?
class CollectionCell: UICollectionViewCell {
@IBOutlet weak var mealImg: UIImageView!
@IBOutlet weak var mealTitleLbl: UILabel!
@IBOutlet weak var gradientView: UIView!
var gradientWasRemoved = false
func configureCell(meal: Meal) {
mealTitleLbl.text = meal.title
let img = meal.getMealImage()
mealImg.image = img
addGradient()
}
func addGradient () {
let gradient = CAGradientLayer()
gradient.frame = gradientView.bounds
let topColor = UIColor(red:0.07, green:0.07, blue:0.07, alpha:1)
let botomColor = UIColor.clear
gradient.colors = [topColor.cgColor, botomColor.cgColor]
gradientView.layer.insertSublayer(gradient, at: 0)
if gradientWasRemoved == true {
gradientView.willMove(toSuperview: self)
}
}
override func prepareForReuse() {
super.prepareForReuse()
gradientView.removeFromSuperview()
gradientWasRemoved = true
}
}
【问题讨论】:
-
在我看来,您的
gradientView是weak,在您拨打gradientView.removeFromSuperview()之后它将为零。 -
你是说渐变视图没有加回来?也许您需要确保在单元格上调用 addSubview ,因为我看不到您将其添加回来。
-
@LeoDabus 使用此代码,不会一次又一次地复制带有渐变的视图?
-
@Luis 当我在 'gradientWasRemoved' 条件检查中添加 'self.addSubview(gradientView)' 时,我的渐变被添加了,但又添加了一个双渐变。
标签: ios swift core-data uicollectionview uicollectionviewcell