Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
- let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MonthCollectionViewCell", for: indexPath) as! MonthCollectionViewCell
- cell.backgroundColor = UIColor.gray
- let firstDate = dates.first
- let index = indexPath.item
- let monthDate = Calendar.current.date(byAdding: .month, value: index, to: firstDate as! Date)
- let monthInt = Calendar.current.component(.month, from: monthDate!)
- let yearInt = Calendar.current.component(.year, from: monthDate!)
- cell.monthLabel.text = String(monthInt)+" "+String(yearInt)
- cell.year = yearInt
- cell.month = monthInt
- let monthDates = dates(self.dates as! [Date], withinMonth: monthInt, withinYear: yearInt)
- cell.colorViews(monthDates:monthDates)
- return cell
- }
- func dates(_ dates: [Date], withinMonth month: Int, withinYear year: Int) -> [Date] {
- let calendar = Calendar.current
- let components: Set<Calendar.Component> = [.month,.year]
- let filtered = dates.filter { (date) -> Bool in
- let monthAndYear = calendar.dateComponents(components, from: date)
- return (monthAndYear.month == month && monthAndYear.year == year)
- }
- return filtered
- }
- class MonthCollectionViewCell: UICollectionViewCell {
- @IBOutlet weak var monthLabel: UILabel!
- @IBOutlet weak var stackView: UIStackView!
- var year: Int?
- var month: Int?
- override func awakeFromNib() {
- super.awakeFromNib()
- for _ in 0...30 { //for the 31 days in a month...
- let tick = UIView()
- self.stackView?.addArrangedSubview(tick)
- }
- }
- func colorViews(monthDates: [Date]){
- for date in monthDates {
- let dayIndex = Calendar.current.component(.day, from: date)
- let tick = stackView.arrangedSubviews[dayIndex]
- tick.backgroundColor = UIColor.red
- }
- }
- }
Add Comment
Please, Sign In to add comment