IOS:模拟日历

时间:2011-04-19 07:44:36

标签: objective-c xcode ios label nsdate

我有这段代码

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 = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd"];
NSString *strDate = [dateFormatter stringFromDate: date];

但现在我希望每个月的每一天都设置31个标签:我如何为每个标签添加此组件?

[components setDay:1];

我也希望所有星期天都是红色的,然后每7天标签必须是红色;你能救我吗?

2 个答案:

答案 0 :(得分:2)

循环是你的朋友:

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];
}

请将yourLabel变量调整为适当的变量。

答案 1 :(得分:0)

这就像@ Eiko的答案,除了在处理夏令时,没有31天的月份等事情时更正确,等等:

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];