我正在使用UICollectionView构建日历。我设法实现了代码,以计算每年每年每个月的日期和星期几。也就是说,如何在单元格的UILabel中显示连续的日期?现在,我只能在所有单元的UILabel中显示1(请参见下文-在这种情况下,9月1日显示)。
ViewController.m
- (NSDateFormatter *)returnDateFormatter {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"dd/MM/yyyy"];
return dateFormatter;
}
-(int)numberOfdaysinMonth:(int)selectedMonthNumber WithDate:(NSDate *)selectedDate
{
NSCalendar* cal = [NSCalendar currentCalendar];
NSDateComponents* comps = [[NSDateComponents alloc] init];
// Set your month here
[comps setMonth:selectedMonthNumber];
NSRange range = [cal rangeOfUnit:NSCalendarUnitDay
inUnit:NSCalendarUnitMonth
forDate:selectedDate];
NSLog(@"%lu", (unsigned long)range.length);
return (int)range.length;
}
-(long)weekDayForDate:(NSDate *)date
{
NSCalendar* cal = [NSCalendar currentCalendar];
NSDateComponents* comp = [cal components:NSCalendarUnitWeekday fromDate:date];
return [comp weekday];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
// static NSString *identifier = @"cell";
CalendarCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
int month = 9;
int year = 2018;
NSDate *date = [[self returnDateFormatter] dateFromString:[NSString stringWithFormat:@"1/%d/%d",month,year]
];
int numberOfDays = [self numberOfdaysinMonth:month WithDate:date];
int index = [self weekDayForDate:date];
NSLog(@"Number Of Days %d", numberOfDays);
NSLog(@"The date is %@", date);
cell.number.text = [NSString stringWithFormat:@"%@", date];
return cell;
}