UITableView部分标题按数组中的date月份

我有一个类似于NSArray的东西:

6/1/13 | Data 6/2/13 | Data 7/1/13 | Data 9/1/13 | Data 

我需要以某种方式得到几个月来创build节标题 – 但只有当它们在数组中,然后将date分成适当的部分。 看起来像:

 (Section Header)June 2013 6/1/13 | Data 6/2/13 | Data (Section Header)July 2013 7/1/13 | Data (skips august as no dates from august are in array) (Section Header)September 2013 9/1/13 | Data 

我正试图执行:

 - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { return @"June 2013"; } 

但显然需要这个dynamic更新与数组中的任何月份。 date实际上是在数组中的NSDates – 如果这有什么区别。

我拼凑了一些至less应该编译的东西,但是完全没有经过testing。 基本上这涉及到预处理数组并将结果存储在其他集合中,然后可以将其作为UITableViewDataSource模型对象。

将这些属性添加到您的数据源的类。 如果您使用ARC,则必须以不同的方式声明它们。

 @property(retain) NSMutableArray* tableViewSections; @property(retain) NSMutableDictionary* tableViewCells; 

将此方法添加到数据源中,并确保在UITableView调用第一个数据源方法之前的某个时间调用它。 重要提示 :您的数组必须包含按sorting顺序排列的NSDate对象(问题中的示例意味着这种情况)。

 - (void) setupDataSource:(NSArray*)sortedDateArray { self.tableViewSections = [NSMutableArray arrayWithCapacity:0]; self.tableViewCells = [NSMutableDictionary dictionaryWithCapacity:0]; NSCalendar* calendar = [NSCalendar currentCalendar]; NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; dateFormatter.locale = [NSLocale currentLocale]; dateFormatter.timeZone = calendar.timeZone; [dateFormatter setDateFormat:@"MMMM YYYY"]; NSUInteger dateComponents = NSYearCalendarUnit | NSMonthCalendarUnit; NSInteger previousYear = -1; NSInteger previousMonth = -1; NSMutableArray* tableViewCellsForSection = nil; for (NSDate* date in sortedDateArray) { NSDateComponents* components = [calendar components:dateComponents fromDate:date]; NSInteger year = [components year]; NSInteger month = [components month]; if (year != previousYear || month != previousMonth) { NSString* sectionHeading = [dateFormatter stringFromDate:date]; [self.tableViewSections addObject:sectionHeading]; tableViewCellsForSection = [NSMutableArray arrayWithCapacity:0]; [self.tableViewCells setObject:tableViewCellsForSection forKey:sectionHeading]; previousYear = year; previousMonth = month; } [tableViewCellsForSection addObject:date]; } } 

现在在你的数据源方法中,你可以说:

 - (NSInteger) numberOfSectionsInTableView:(UITableView*)tableView { return self.tableViewSections.count; } - (NSInteger) tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section { id key = [self.tableViewSections objectAtIndex:section]; NSArray* tableViewCellsForSection = [self.tableViewCells objectForKey:key]; return tableViewCellsForSection.count; } - (NSString*) tableView:(UITableView*)tableView titleForHeaderInSection:(NSInteger)section { return [self.tableViewSections objectAtIndex:section]; } [...] 

剩下的实现作为一个练习留给你:-)每当你的数组内容发生变化时,你显然需要调用setupDataSource:更新tableViewSectionstableViewCells的内容。

您需要转换现有的单个数组并创build一个新的字典数组。 这个新数组中的每个字典将包含两个条目 – 一个为一个月份,另一个条目为包含与该月份相关的每行数据的数组。

如果您需要在此结构中添加新行,请查看该月份是否已在列表中。 如果是这样,更新该月份的数组。 否则,用新的月份和包含一个新行的新数组创build一个新的字典。