我们使用UICollectionView来绘制日历。 补充视图用于表示日历中某一天的列顶部的日期。 每个日历都是 UICollectionView 中的一个部分。 我们希望突出显示当前一天。 我们通过以下方式工作
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
var view: UICollectionReusableView?
if kind == WeeklyCollectionElementKindDayColumnHeader {
let dayColumnHeader: WeeklyDayColumnHeader? = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: WeeklyDayColumnHeaderReuseIdentifier, for: indexPath) as? WeeklyDayColumnHeader
let day: Date? = collectionViewCalendarLayout?.dateForDayColumnHeader(at: indexPath)
let currentDay: Date? = currentTimeComponents(for: self.collectionView!, layout: collectionViewCalendarLayout!)
let startOfDay: Date? = Calendar.current.startOfDay(for: day!)
let startOfCurrentDay: Date? = Calendar.current.startOfDay(for: currentDay!)
dayColumnHeader?.day = day
dayColumnHeader?.isCurrentDay = startOfDay == startOfCurrentDay
view = dayColumnHeader
}
else if kind == WeeklyCollectionElementKindTimeRowHeader {
let timeRowHeader: WeeklyTimeRowHeader? = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: WeeklyTimeRowHeaderReuseIdentifier, for: indexPath) as? WeeklyTimeRowHeader
timeRowHeader?.time = collectionViewCalendarLayout?.dateForTimeRowHeader(at: indexPath)
view = timeRowHeader
}
return view!
}
其中有这个
class WeeklyDayColumnHeader: UICollectionReusableView {
var day: Date? {
didSet {
var dateFormatter: DateFormatter?
if dateFormatter == nil {
dateFormatter = DateFormatter()
dateFormatter?.dateFormat = "E d"
}
self.title!.text = dateFormatter?.string(from: day!)
setNeedsLayout()
}
}
var isCurrentDay: Bool = false {
didSet {
if isCurrentDay {
title?.textColor = UIColor.white
title?.font = UIFont.boldSystemFont(ofSize: CGFloat(16.0))
titleBackground?.backgroundColor = UIColor(red:0.99, green:0.22, blue:0.21, alpha:1.0)
}
else {
title?.font = UIFont.systemFont(ofSize: CGFloat(16.0))
title?.textColor = UIColor.black
titleBackground?.backgroundColor = UIColor.clear
}
}
}
设置我第一次进入此视图时想要的背景。 但是,如果我打开此视图并且日期更改,如何更新标题? 我应该将设置日期的逻辑移动到哪里,我如何"无效"或我需要做什么?
使用UIApplicationSignificantTimeChangeNotification
来通知您时间变化。
使用NotificationCenter
来实现这一点。像这样:
NotificationCenter.defaultCenter().addObserver(self, selector: "dayChanged:", name: UIApplicationSignificantTimeChangeNotification, object: nil)
然后你需要一个函数来处理更改:
func dayChanged(notification: NSNotification){
// trigger the changes you need here
}