CollectionView cell unexpected behaviour swift

My cells get created based on timeSlotArray with holds all the opening time time slots in 30 minutes increments, but gets its color based on if it's Id is equal to any of the bookedTimeSlotsArray entries IDs. If I select a day that have bookings, it gets the cells the right colour, but cells will keep that color on reloading data, even if I change to a date with other bookings.

The function is:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "timeSlotCell", for: indexPath) as! TimeSlotCollectionViewCell

    // Configure the cell
    cell.timeLabel.text = timeSlotArray[indexPath.row]

    cell.cellId = Int("\(String(describing: self.selectedDate))" + self.timeStringToStringConvert(timeSlotArray[indexPath.row]))

    if bookedTimeSlotsArray.count > 0 {
        for index in 0...bookedTimeSlotsArray.count - 1 {
            let bookingId = bookedTimeSlotsArray[index].bookingId

            if cell.cellId == bookingId {
                print("   match found")
                print("Index is: \(index)")
                print("cell time is: \(timeSlotArray[indexPath.row])")
                print("time slot cell id is: \(String(describing: cell.cellId))")
                print("booking id: \(bookingId)")
                cell.backgroundColor = UIColor.red.withAlphaComponent(0.3)
            } else {
                cell.backgroundColor = UIColor.green.withAlphaComponent(0.8)

            }
        }
    }
    return cell
}

I reload collection view data in 2 functions, calculateOpenTimeSlots()andcalculateBookedTimeSlots()and they get called like this: 1st case: in viewDidLoad()I call both functions, 2nd case: in Firebaseobserver function I call only calculateBookedTimeSlots(), 3rd case: in changing day from selecting table view cell I call only calculateOpenTimeSlots()in didSelectRowAt. 1st and 3rd cases are working as expected, but 2nd is not as described at the beginning of the question. Can you guys se where I'm hitting the wall?? Many thanks as usual.

EDIT:

I added a prepareForReuse to my cell`s class but I still get the same behaviour when collection view draws the cells. Here's the cell class:

import UIKit

class TimeSlotCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var timeLabel: UILabel!

    var cellId: Int!

    override func prepareForReuse() {
        super.prepareForReuse()
        // Set your default background color, title color etc
        backgroundColor = UIColor.green.withAlphaComponent(0.8)
    }

}

1 answer

  • answered 2019-02-10 16:30 Vincenzo

    Found the problem. I cancelled the elsestatement after if statement in cellForItemAtas now prepareForReuseis setting the default cell. It all now works as expected. The final function is:

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "timeSlotCell", for: indexPath) as! TimeSlotCollectionViewCell
    
            // Configure the cell
            cell.timeLabel.text = timeSlotArray[indexPath.row]
    
            cell.cellId = Int("\(String(describing: self.selectedDate))" + self.timeStringToStringConvert(timeSlotArray[indexPath.row]))
    
            if bookedTimeSlotsArray.count > 0 {
                for index in 0...bookedTimeSlotsArray.count - 1 {
                    let bookingId = bookedTimeSlotsArray[index].bookingId
    
                    if cell.cellId == bookingId {
                        print("   match found")
                        print("Index is: \(index)")
                        print("cell time is: \(timeSlotArray[indexPath.row])")
                        print("time slot cell id is: \(String(describing: cell.cellId))")
                        print("booking id: \(bookingId)")
                        cell.backgroundColor = UIColor.red.withAlphaComponent(0.3)
                    }
                }
            }
            return cell
        }