Ios 从周编号中获取日期,节标题编号为周
好的。。。所以我尝试使用UITableView,并将其分为52个部分。。一年中有52周。。。每个部分每周有7天(单元格)。我想让每个章节的标题写上“一年中的一周”。每次我试图在相应周的headerSection中打印字符串时,都没有显示任何内容。有没有办法使用标题节编号将该周日期的第一天设置到标题节中?下面是我一直在努力工作的代码。。。这似乎是有道理的。但我做错了什么。我真的很感激任何帮助。先谢谢你Ios 从周编号中获取日期,节标题编号为周,ios,objective-c,ios4,Ios,Objective C,Ios4,好的。。。所以我尝试使用UITableView,并将其分为52个部分。。一年中有52周。。。每个部分每周有7天(单元格)。我想让每个章节的标题写上“一年中的一周”。每次我试图在相应周的headerSection中打印字符串时,都没有显示任何内容。有没有办法使用标题节编号将该周日期的第一天设置到标题节中?下面是我一直在努力工作的代码。。。这似乎是有道理的。但我做错了什么。我真的很感激任何帮助。先谢谢你 - (NSString *)tableView:(UITableView *)tableView
- (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;
}
我不知道为什么您决定在代码中使用switch语句,但它毫无用处,至少会导致一些问题。除了三周(switch语句中包含的三个案例),titleForHeaderSection:方法将返回零。相反,您应该尝试以下方法:
- (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];
}
请注意,我在上面设置了工作日,而不是日期,因为我相信您正在尝试获取该周第一天的日期。它非常有效。再次感谢你,你不知道我有多感激你的帮助。我花了几天的时间在这件事上。另外,如果你不介意的话,你认为在每一行中输入一个月的天数的最佳方式是什么?例如,第0节将是第22、23、24、25、26、27、28节,下一节将从第29节继续,依此类推。我是否应该创建一个包含所有这些周的plist,每周7天?创建一个包含365个字符的数组似乎有点多余。您可以向
tableView:cellforrowatinexpath:
方法中添加与上面类似的代码,因为nsindepath同时提供节号和行号。或者,您可以在viewdiload:
中计算节标题和行标题,并将它们存储在两个nsarray中,只需在titleForHeaderInSection:
和cellforrowatinexpath:
方法中获取这些值即可。再次感谢。这需要一点操作,但效果很好。你确定一年有52周吗?