如何在UICollectionView

时间:2017-06-30 14:06:18

标签: ios swift uicollectionview uicollectionreusableview

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

    }
}

在我第一次进入此视图时设置我们想要的背景。但是,如果我打开此视图并更改日期,如何更新标题?我应该在哪里移动设置日期的逻辑,以及如何使#34;无效"或者我需要做什么?

1 个答案:

答案 0 :(得分:0)

使用UIApplicationSignificantTimeChangeNotification通知您时间变化。

使用NotificationCenter来实现此目的。像这样:

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

然后你需要一个处理变化的函数:

func dayChanged(notification: NSNotification){

    // trigger the changes you need here
}