Reputation: 13
Im having a weird situation when reloading a collection view, before reloading I remove all object from the source then fetch it after that I'm calling reloadData on my collection and for some reason the collection is adding view but never remove them. (the dataSource doesn't have duplicate the array is always correct)
When I call a reload :
viewModel.reloadActivities()
activityCollection.reloadData()
This method in the viewModel fetch the data and replace the array used by the data source :
func reloadActivities() {
activities.removeAll()
fetchActivities()
}
Here is an Activity Cell:
func configure(with activity: Activity) {
self.displayActivityCell(with: activity)
}
func displayActivityCell(with activity: Activity) {
let background = UIView(frame: CGRect(x: 0, y: 0, width: contentView.frame.width, height: 100))
background.backgroundColor = #colorLiteral(red: 0.9764705896, green: 0.850980401, blue: 0.5490196347, alpha: 1)
contentView.addSubview(background)
let label = UILabelFactory(text: activity.getMessage()).color(.black).draw()
contentView.addSubview(label)
label.topAnchor == background.topAnchor + 10
label.leadingAnchor == background.leadingAnchor
label.trailingAnchor == background.trailingAnchor
label.translatesAutoresizingMaskIntoConstraints = false
}
But here is the result if I call the reload X times...
Any hint why the reloadData doesn't "clean" the added contentView?
Thanks
Upvotes: 0
Views: 180
Reputation: 1029
Because the object and UI elements are separated. Reload data is only for data. Do you call configure(with activity: Activity)
in the view controller's cellForRow at indexpath ? if so, it will always create a new background view and adding it into contentView's subview.
How about moving out the background
and label to cell's init method.
Inside the displayActivityCell
function, you should only customise things that are changing, like this ...
func displayActivityCell(with activity: Activity) {
background.backgroundColor = #colorLiteral(red: 0.9764705896, green: 0.850980401, blue: 0.5490196347, alpha: 1)
label.text = activity.getMessage()
}
Upvotes: 1