我的应用包含时间表(UITableView
)和日期栏(UICollectionView
)。用户可以通过以下两种方法之一更改其选定日期:
现在的问题是,当我在第二天尚未滚动到屏幕的情况下单击它时,未选择当天的单元格(见下文)。
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)
}
答案 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)