画日历。最简单的日历。通过NSCalendar和UICollectionView来操作。
1.主要的内容是获取。当前月份的范围。上一个月的遗留天数。下一月空出的天数。核心代码。
1 - (void)FF_CalendarDataCode 2 { 3 /// 获取当前月份的范围 4 NSCalendar *calendar = [NSCalendar currentCalendar]; 5 NSRange currentRange = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:[NSDate date]]; 6 NSDateComponents *currentComponents = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[NSDate date]]; 7 /// 获取当月的第一天是周几 8 currentComponents.day = 1; 9 NSInteger startWeak = [calendar component:NSCalendarUnitWeekday fromDate:[calendar dateFromComponents:currentComponents]]; 10 /// 获取当月的最后一天是周几(从周日-周为0-7) 11 currentComponents.day += currentRange.length - 1; 12 NSInteger endWeak = [calendar component:NSCalendarUnitWeekday fromDate:[calendar dateFromComponents:currentComponents]]; 13 /// 获取上个月份范围 14 NSDateFormatter *lastFormatter= [[NSDateFormatter alloc] init]; 15 lastFormatter.dateFormat = @"yyyy-MM-dd"; 16 NSCalendar *lastCanlendar = [NSCalendar currentCalendar]; 17 NSDateComponents *lastComponents = [lastCanlendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[NSDate date]]; 18 if (lastComponents.month > 1) { 19 lastComponents.month -= 1; 20 }else { 21 lastComponents.year -= 1; 22 lastComponents.month = 12; 23 } 24 lastComponents.day = 1; 25 NSRange lastMonthRange = [lastCanlendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:[lastFormatter dateFromString:[NSString stringWithFormat:@"%ld-%02ld-%02ld", lastComponents.year, lastComponents.month, lastComponents.day]]]; 26 /// 获取上个月剩余的天数 27 NSMutableArray *lastMonthArr = [NSMutableArray arrayWithCapacity:0]; 28 for (NSUInteger i = lastMonthRange.length - startWeak + 2; i <= lastMonthRange.length; i++) { 29 [lastMonthArr addObject:[NSString stringWithFormat:@"%02ld", i]]; 30 } 31 /// 获取本月的天数 32 NSMutableArray *currentMonthArr = [NSMutableArray arrayWithCapacity:0]; 33 for (NSUInteger i = 1; i <= currentRange.length; i ++) { 34 [currentMonthArr addObject:[NSString stringWithFormat:@"%02ld", i]]; 35 } 36 /// 获取下个月需要展示的天数 37 NSMutableArray *nextMonthArr = [NSMutableArray arrayWithCapacity:0]; 38 for (NSUInteger i = 1; i <= 7 - endWeak; i++) { 39 [nextMonthArr addObject:[NSString stringWithFormat:@"%02ld", i]]; 40 } 41 /// 需要展示的数据 42 NSMutableArray *dataArray = [NSMutableArray arrayWithArray:lastMonthArr]; 43 [dataArray addObjectsFromArray:currentMonthArr]; 44 [dataArray addObjectsFromArray:nextMonthArr]; 45 NSLog(@"------- %@ %@ %@ ", lastMonthArr, currentMonthArr, nextMonthArr); 46 }