Reputation: 2072
I have a calendarView
made up of collectionView
. It is a custom calendarView
derived using mathematical calculations.
The seventh row marks Saturday and it's holiday so the font color is red for the all the labels of seventh column.
However, when I swipe or navigate to other days, the red color labels are scattered in random order which is untraceable. A screenshot is herewith:
How did this occur?
In my dequeueReusableCell
method I have cell configured for holiday as:
cell.isHoliday = (indexPath.row + 1) % 7 == 0 ? true : false
And this is the logic for holiday in my custom collectionViewCell
.
@IBOutlet var dateLabel: UILabel!
@IBOutlet var englishDateLabel: UILabel!
@IBOutlet var tithiLabel: UILabel!
var isToday: Bool = false {
didSet {
self.contentView.backgroundColor = isToday ? Colors.Palette.LightGreen : UIColor.white
}
}
var isHoliday: Bool = false {
didSet {
if isHoliday {
tithiLabel.textColor = Colors.Palette.DarkRed
dateLabel.textColor = Colors.Palette.DarkRed
englishDateLabel.textColor = Colors.Palette.DarkRed
}
else {
dateLabel.textColor = UIColor.black
englishDateLabel.textColor = UIColor.black
}
}
}
The number of red labels on top of each collectionview cells goes on increasing as I swipe to next month. Why is this happening and how can I stop this from happening?
Upvotes: 1
Views: 97
Reputation: 6775
The right way to deal with old data showing up in reused cells is to override prepeareForReuse
in your custom cell
open override func prepareForReuse() {
super.prepareForReuse()
tithiLabel.textColor = UIColor.black
dateLabel.textColor = UIColor.black
englishDateLabel.textColor = UIColor.black
}
Clear out old values (by assigning them to nil
) or set defaults to all values that might not necessarily be set after the cell is reused. This way, even if the new value(s) are not explicitly set to the cell, you are sure that old values are not being retained.
Upvotes: 1
Reputation: 945
This may be because the cell is being reused and you are not implemented any logic in prepareForReuse method of your custom cell class. In this method try setting text colour properties to nil.
Upvotes: 1
Reputation: 387
You are missing else part:
var isHoliday: Bool = false {
didSet {
if isHoliday {
tithiLabel.textColor = Colors.Palette.DarkRed
dateLabel.textColor = Colors.Palette.DarkRed
englishDateLabel.textColor = Colors.Palette.DarkRed
}
else {
tithiLabel.textColor = UIColor.black
dateLabel.textColor = UIColor.black
englishDateLabel.textColor = UIColor.black
}
}
}
Upvotes: 1