如何更改屏幕上尚未显示的单元格的属性?

时间:2017-06-01 08:50:35

标签: ios swift uicollectionview

我的应用包含时间表(UITableView)和日期栏(UICollectionView)。用户可以通过以下两种方法之一更改其选定日期:

  1. 从DayBar中选择一天
  2. 点击表格视图底部的“JumpToTomorrow”按钮。
  3. 现在的问题是,当我在第二天尚未滚动到屏幕的情况下单击它时,未选择当天的单元格(见下文)。 enter image description here

    DayCollectionViewCell.isSelected (由于某种原因未被调用)

        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功能

        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)
    }
    

3 个答案:

答案 0 :(得分:1)

您应修改collectionView(_:cellForItemAt:)以检查是否应选择单元格索引并更新其中的样式。

答案 1 :(得分:1)

我编辑了我的答案。实际上你必须手动设置isSelected。

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

答案 2 :(得分:1)

禁用预取已修复此问题。

enter image description here