Trying to update a collection view when tableview

2019-09-02 06:59发布

问题:

I have In the same view controller a calendarTableview that represent a month and a timeSlotCollectionView that represent the current day opening time divided in 30 min slots. My intent is that at loading the view controller inside calendarTableview cellForRowAt I check if it's current day and set it as selected, and load the timeSlotCollectionViewwith again a certain criteria. It all works es expected only when I physically select the row, triggering didSelectRowAtbut not on first load. All the updating is done by a function that I call in both cellForRowAtand didSelectRowAt, but on load is not updating timeSlotCollectionView. I had a similar problem in the next stage of my app, when you actually select a time slot and with my previous question has been solved, but I can't apply that in this scenario. Can you see where I'm mistaking this time?

The functions are:
for calendarTableView

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

            let cell = tableView.dequeueReusableCell(withIdentifier: "calendarCell", for: indexPath) as! CalendarTableViewCell

            // Configure the cell...

            let date = datesArray[indexPath.row]
            print(date)

            let calendar = Calendar.current
            let components = calendar.dateComponents([.year, .month, .day, .weekday], from: date)

            cell.dayLabel.text = "\(String(describing: components.day!))" + " " + "\(dayNamesArray[components.weekday! - 1])"
            cell.cellWeekday = components.weekday!
            print("cell weekday is: \(cell.cellWeekday!)") // prints correct weekday

            cell.cellId = "\(String(format:"%04d", components.year!))" + "\(String(format:"%02d", components.month!))" + "\(String(format:"%02d", components.day!))"
            self.selectedDate = cell.cellId // used for time slots cellId

            // highlighting current day cell
            if indexPath.row == self.actualDay - 1 && self.actualMonth == self.displayedMonth {

                cell.dayLabel.backgroundColor = UIColor.red.withAlphaComponent(0.3)

                // emulate user selecting the cell
                tableView.selectRow(at: indexPath, animated: false, scrollPosition: UITableViewScrollPosition.none) // changing to .middle makes the tableview go looping
                print(" @@@@@@@@@@@@@@@@@@@@@@@@@@   selected cell weekday is: \(cell.cellWeekday!) @@@@@@@@@@@@@@@@@@@@ ")

                self.updateTimeSlots(selectedCell: cell)
    //            self.actualWeekday = cell.cellWeekday!
    //            self.selectedDate = cell.cellId
    //            calculateOpenTimeSlots()

            }
            let cornerRadius: CGFloat = 5
            cell.layer.cornerRadius = cornerRadius
            cell.clipsToBounds = true
            return cell
        }


        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            let cell = tableView.cellForRow(at: indexPath) as! CalendarTableViewCell
            self.updateTimeSlots(selectedCell: cell)
    //        self.actualWeekday = cell.cellWeekday!
    //        self.selectedDate = cell.cellId
    //        print(" selected cell weekday is: \(cell.cellWeekday!)")
    //        calculateOpenTimeSlots()

        }

for timeSlotCollectionView:

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

            // Configure the cell
            cell.timeLabel.text = timeSlotArray[indexPath.row]
            cell.cellId = Int64("\(String(describing: self.selectedDate))" + self.timeStringToStringConvert(timeSlotArray[indexPath.row]))!


            // method two USING fetchResultController 
            if (self.fetchedResultController.fetchedObjects?.count)! > 0 {
                        for value in self.fetchedResultController.fetchedObjects! {
                            if Int64(value.bookingId!) == cell.cellId {
                                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.8)
                                cell.bookingState.backgroundColor = UIColor.red.withAlphaComponent(0.8)
                            }
                        }
            }


            print(" cell.cellId is : \(String(describing: cell.cellId!))")
            print("    @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ time slot created @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@    ")



   // Method one : USING ARRAY works in realtime
//        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.8)
//                    cell.bookingState.backgroundColor = UIColor.red.withAlphaComponent(0.8)
//                }
//            }
//        }
        return cell
    }

and the values updating :

func updateTimeSlots(selectedCell: CalendarTableViewCell) {

            self.actualWeekday = selectedCell.cellWeekday!
            self.selectedDate = selectedCell.cellId
            print(" selected cell weekday is: \(selectedCell.cellWeekday!)")
            fetchBookings()
            calculateOpenTimeSlots()

        }

Can it be a time lag between the cells creation of the two? In my other question this was the case. Many thanks as always.

回答1:

I found what the problem was. I was refreshing timeSlotCollectionViewin a function that calculated the booked time slots. I guess that there was I little time gap between the array being populated from that function and timeSlotCollectionViewreading from that array to draw its cells, resulting in plain cells. I modified cellForItemAt so I can perform the check for condition directly from fetched results and that way I could bypass that function. Now the correct cell in calendarTableView gets selected and timeSlotCollectionViewgets populated with correct cells. I hope that this could help others facing the same problem.

This is the new function:

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

        // Configure the cell
        cell.timeLabel.text = timeSlotArray[indexPath.row]
        cell.cellTime = timeSlotArray[indexPath.row]
        cell.cellId = Int64("\(String(describing: self.selectedDate))" + self.timeStringToStringConvert(timeSlotArray[indexPath.row]))!


        // method two USING fetchResultController 
        if (self.fetchedResultController.fetchedObjects?.count)! > 0 {
            for valueStart in self.fetchedResultController.fetchedObjects! {
                // booking start match

                if timeStringToStringConvert(cell.cellTime) == timeStringToStringConvert(valueStart.bookingStart!) {//} && cell.cellTime <= timeStringToStringConvert(valueStart.bookingEnd!) {

                    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: \(valueStart.bookingId!)")
                    //                    cell.backgroundColor = UIColor.red.withAlphaComponent(0.8)
                    cell.bookingState.backgroundColor = UIColor.red.withAlphaComponent(0.8)
                    cell.backgroundColor = UIColor.red.withAlphaComponent(0.25)


                }

                else if timeStringToStringConvert(cell.cellTime) > timeStringToStringConvert(valueStart.bookingStart!) && timeStringToStringConvert(cell.cellTime) < timeStringToStringConvert(valueStart.bookingEnd!){

                    print(" Mid slot found")
                    print(" mid slot id is: \(String(describing: cell.cellId))")
                    cell.bookingState.backgroundColor = UIColor.red.withAlphaComponent(0.3)
                    cell.backgroundColor = UIColor.red.withAlphaComponent(0.15)
                    cell.isUserInteractionEnabled = false

                }


                print("bookingId is: \(valueStart.bookingId!)")

            }
        }