好的...所以我正在尝试使用UITableView并将其划分为52个部分..一年中52周...每个部分有一周7天(单元格)。我希望每个部分的头部都说“每月一周,一年”。每次我尝试在相应周的headerSection中打印字符串时都没有显示。有没有办法使用标题部分编号将该周日期的第一天设置为sectionHeader?下面是我一直试图开始工作的代码......看起来它是有道理的。但我做错了什么。我真的很感激任何帮助。提前谢谢。
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSDate *now = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comp = [gregorian components:NSYearCalendarUnit fromDate:now];
[comp setWeek:section];
[comp setDay:1];
NSDate *resultDate = [gregorian dateFromComponents:comp];
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"EEE, MMM d, ''yy"];
NSString *myDateString = [formatter stringFromDate:resultDate];
NSString *sectionHeader = nil;
switch (section) {
case 0:
sectionHeader = myDateString;
break;
case 1:
sectionHeader = myDateString;
break;
case 2:
sectionHeader = myDateString;
break;
default:
break;
}
return sectionHeader;
}
答案 0 :(得分:2)
我不确定你为什么决定在代码中使用switch语句,但它绝对没有任何意义,至少会导致你的一些问题。对于除了三周之外的所有情况(switch语句中包含的三种情况),titleForHeaderSection:方法将返回nil。相反,你应该尝试这样的事情:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSDate *now = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comp = [gregorian components:NSYearCalendarUnit fromDate:now];
[comp setWeek:(section + 1)]; // section numbers start at 0, so need to add 1
[comp setWeekDay:1]; // Note that this is very different than setting day to 1
NSDate *resultDate = [gregorian dateFromComponents:comp];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMM d, yyyy"];
NSString *myDateString = [formatter stringFromDate:resultDate];
[gregorian release]; // Clean up allocated objects by releasing them
[formatter release];
return [NSString stringWithFormat:@"Week of %@", myDateString];
}
请注意,我将工作日设置在上方,而不是当天,因为我相信您正在尝试获取该周第一天的日期。