我有一个UICollectionViewCell:
" Gradient View"是一个有渐变的UIView:
数据来源是CoreData。 在Collection视图中,我有对CoreData进行排序的按钮:
@IBAction func allMealsBtn(_ sender: Any) {
let fetchRequest: NSFetchRequest<Meal> = Meal.fetchRequest()
let dateSort = NSSortDescriptor(key: "created", ascending: false)
fetchRequest.sortDescriptors = [dateSort]
let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
controller.delegate = self
self.controller = controller
do {
try controller.performFetch()
} catch {
let error = error as NSError
print("Couldn't fetch data from CoreData with error: \(error.debugDescription)")
}
collectionView.reloadData()
}
按下排序按钮后,集合视图将重新加载并显示正确的数据。 但是,渐变视图会增加,就好像细胞没有被破坏一样。 这是我多次排序数据后看到的内容:
如何确保我的单元格从头开始重绘?
修改:
我的自定义单元格类。 所以在configureCell中我必须检查我的gradientView是否添加到视图中,如果是,则添加渐变,如果没有,添加它,并添加渐变。 我怎么做这个检查?
class CollectionCell:UICollectionViewCell {
@IBOutlet weak var mealImg: UIImageView!
@IBOutlet weak var mealTitleLbl: UILabel!
@IBOutlet weak var gradientView: UIView!
func configureCell(meal: Meal) {
mealTitleLbl.text = meal.title
let img = meal.getMealImage()
mealImg.image = img
gradientView.addGradientWithColor(color: UIColor.clear)
// How can I check if my gradientView is added to the view, if yes, then add gradient, if not, add it, and only then add gradient.
}
override func prepareForReuse() {
super.prepareForReuse()
gradientView.removeFromSuperview()
}
}
extension UIView {
func addGradientWithColor(color: UIColor) {
let gradient = CAGradientLayer()
gradient.frame = self.bounds
let topColor = UIColor(red:0.07, green:0.07, blue:0.07, alpha:1)
gradient.colors = [topColor.cgColor, color.cgColor]
self.layer.insertSublayer(gradient, at: 0)
}
}
修改 我删除了扩展并实现了标志逻辑。 但是,在删除视图后,执行搜索后它永远不会再出现在单元格上。 有什么想法吗?
class CollectionCell: UICollectionViewCell {
@IBOutlet weak var mealImg: UIImageView!
@IBOutlet weak var mealTitleLbl: UILabel!
@IBOutlet weak var gradientView: UIView!
var isGradientAdded = false
func configureCell(meal: Meal) {
mealTitleLbl.text = meal.title
let img = meal.getMealImage()
mealImg.image = img
if isGradientAdded == false {
addGradient()
isGradientAdded = true
}
}
override func prepareForReuse() {
super.prepareForReuse()
gradientView.removeFromSuperview()
}
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)
}
}
答案 0 :(得分:0)
在UICollectionViewCell
子类(Cell)中,您应该覆盖prepeareForReuse
函数 - 将单元格设置为默认模式。
如果您没有Cell
的自定义类 - 之前创建它并在界面构建器中指定为Cell
单元格的类(当然不要忘记出口)
override func prepareForReuse() {
super.prepareForReuse()
//set cell to initial state here
//e.g try to remove you gradient view
yourGradientView.removeFromSuperview()
}