当tableview单元格匹配标准Swift时尝试更新集合视图

Posted

技术标签:

【中文标题】当tableview单元格匹配标准Swift时尝试更新集合视图【英文标题】:Trying to update a collection view when tableview cell matches a criteria Swift 【发布时间】:2019-04-11 17:24:43 【问题描述】:

我在同一个视图控制器中有一个 calendarTableview 代表一个月和一个 timeSlotCollectionView 代表当天开放时间分为 30 分钟的时段。我的意图是在 calendarTableview cellForRowAt 中加载视图控制器时,我会检查它是否是当前日期并将其设置为选中,然后再次使用特定标准加载 timeSlotCollectionView。只有当我物理选择行时,这一切都可以正常工作,触发didSelectRowAt,但不是在第一次加载时。所有更新都是由我在cellForRowAtdidSelectRowAt中调用的函数完成的,但在加载时不会更新timeSlotCollectionView。我在我的应用程序的下一阶段遇到了类似的问题,当您实际选择一个时间段并且我之前的问题已经解决时,但我无法在这种情况下应用它。你能看出我这次错在哪里了吗?

功能有: 为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()

        

对于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
    

和值更新:

func updateTimeSlots(selectedCell: CalendarTableViewCell) 

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

        

这两者的细胞创建之间会不会有时间差?在我的另一个问题中就是这种情况。非常感谢一如既往。

【问题讨论】:

【参考方案1】:

我发现了问题所在。我在计算预订时隙的函数中刷新timeSlotCollectionView。我猜想从该函数填充数组与从该数组中读取 timeSlotCollectionViewreading 以绘制其单元格之间几乎没有时间间隔,从而产生普通单元格。我修改了cellForItemAt,因此我可以直接从获取的结果中执行条件检查,这样我就可以绕过该功能。现在calendarTableView 中的正确单元格被选中,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.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!)")

            
        

【讨论】:

以上是关于当tableview单元格匹配标准Swift时尝试更新集合视图的主要内容,如果未能解决你的问题,请参考以下文章

重用自定义 tableView 单元格时重复显示相同的子视图(Swift 4.1)

Swift tableView.reloadRows 删除单元格

Swift - 选择 TableView 单元格时动画(didSelectRowAtIndexPath)

向下滚动时不会出现 Swift Expandable tableView 单元格按钮

调整 TableView 大小时,Swift 3.0 表格单元格未填充

在 swift 中初始化时 tableview 的单元格不是 nil