How to change the properties of a cell that is not yet displayed on the screen?

I have an application consisting of a schedule ( UITableView) and a day panel ( UICollectionView). The user can change his chosen day in one of two ways:

  • Choose a day from DayBar
  • Click the "JumpToTomorrow" button at the bottom of the table view.

The problem with 2. right now is that when I click it in a scenario where the next day is not yet scrolling on the screen, the cell for that day is not selected (see below). enter image description here

DayCollectionViewCell.isSelected (not called for any reason)

    override var isSelected: Bool {
    didSet {
        self.backgroundColor        = self.getBackgroundColor(selected: isSelected)
        self.layer.borderColor      = self.getBorderColor(selected: isSelected)
        self.number.attributedText  = NSAttributedString(string: number.text!, attributes: self.getTextAttributes(selected: isSelected))
    }
}

DayBarController Functions

    override func viewDidLoad() {
    super.viewDidLoad()
    // To preserve selection between presentations
    self.clearsSelectionOnViewWillAppear = false
    setEdgeInsets()
    BroadcastManager.listen(to: PrepNotifications.JumpToTomorrowClicked, listenerId: "UpdateSelectedDay", react: updateSelectedDay)
}
    /// change the selected day and notify the app about the change
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    PrepGlobals.Calendar.SELECTED_DAY = indexPath.row
    BroadcastManager.broadcast(PrepNotifications.SelectedDayChanged)
    //scroll to center on selected day in case of clicked on today  
    if (PrepGlobals.Calendar.TODAY_INDEX == indexPath.row){
        self.collectionView?.scrollToItem(
            at: indexPath,
            at: .centeredHorizontally,
            animated: true
        )
    }
}

private func updateSelectedDay(_ userInfo: [AnyHashable: Any]? = nil) {
    PrepGlobals.Calendar.SELECTED_DAY += 1
    let selectedDayIndex = IndexPath(row: PrepGlobals.Calendar.SELECTED_DAY, section: 0)
    self.collectionView!.selectItem(at: selectedDayIndex, animated: true, scrollPosition: .right)
    BroadcastManager.broadcast(PrepNotifications.SelectedDayChanged)
}
+4
source share
3 answers

. isSelected .

override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
      cell.isSelected = (indexPath.row == PrepGlobals.Calendar.SELECTED_DAY)
}
+1

collectionView(_:cellForItemAt:), , , .

+1

Disable prefetch fixed.

enter image description here

+1
source

Source: https://habr.com/ru/post/1678324/


All Articles