如何在 UICollectionView 的补充视图中触发刷新

How to trigger refresh in Supplementary view of UICollectionView

我们正在使用 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
        }

    }
}

第一次进入这个视图时设置我们想要的背景。但是如果我打开这个视图并且日期发生变化,我该如何更新 header?我应该将设置日期的逻辑移到哪里,我该如何 "invalidate" 或者我需要做什么?

使用 UIApplicationSignificantTimeChangeNotification 通知您时间更改。

使用 NotificationCenter 来实现它。像这样:

NotificationCenter.defaultCenter().addObserver(self, selector: "dayChanged:", name: UIApplicationSignificantTimeChangeNotification, object: nil)

那么你需要一个函数来处理这个变化:

func dayChanged(notification: NSNotification){

    // trigger the changes you need here
}