IOS: simulate a calendar
I have this code
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setYear:2011];
[components setDay:1];
[components setMonth:7];
NSCalendar *gregorianCalendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDate *date = [gregorianCalendar dateFromComponents:components];
NSDateFormatter *dateFormatter = [[NSDateForm开发者_如何转开发atter alloc] init];
[dateFormatter setDateFormat:@"dd"];
NSString *strDate = [dateFormatter stringFromDate: date];
but now I want set 31 labels for each day of my month: how I can add this component for each label?
[components setDay:1];
and I also I want that all sundays are red, then avery 7 days label must be red color; can you help me?
Loops are your friend:
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setYear:2011];
[components setDay:1];
[components setMonth:7];
NSCalendar *gregorianCalendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDate *firstDate = [gregorianCalendar dateFromComponents:components];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd"];
for (int i = 0; i < 31; i++) {
NSTimeInterval seconds = 24*60*60 * i;
NSDate *date = [NSDate dateWithTimeInterval:seconds sinceDate:firstDate];
NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit fromDate:date];
int weekday = [weekdayComponents weekday];
NSString *strDate = [dateFormatter stringFromDate: date];
yourLabel.text = strDate;
yourLabel.textColor = weekday == 1 ? [UIColor redColor : blackColor];
}
Please adjust the yourLabel
variable to the appropriate ones.
This is like @Eiko's answer, except more correct when dealing with things like daylight savings time, months that don't have 31 days, etc:
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setYear:2011];
[components setMonth:7];
[components setDay:1];
NSCalendar *gregorianCalendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDate *startDate = [gregorianCalendar dateFromComponents:components];
NSRange rangeOfDays = [gregorianCalendar rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:startDate];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd"];
for (NSInteger i = 1; i <= NSMaxRange(rangeOfDays); ++i) {
[components setDay:i];
NSDate *date = [gregorianCalendar dateFromComponents:components];
yourLabel.text = [dateFormatter stringFromDate: date];
NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit fromDate:date];
int weekday = [weekdayComponents weekday];
yourLabel.textColor = weekday == 1 ? [UIColor redColor : blackColor];
}
[dateFormatter release];
精彩评论