Ios UITableView按数组中日期的月份显示节标题
我有一个类似的NSArray:Ios UITableView按数组中日期的月份显示节标题,ios,objective-c,uitableview,nsarray,Ios,Objective C,Uitableview,Nsarray,我有一个类似的NSArray: 6/1/13 | Data 6/2/13 | Data 7/1/13 | Data 9/1/13 | Data 我需要以某种方式获得创建节标题的月份,但前提是它们在数组中,然后将日期分解为适当的节。看起来像: (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 a
6/1/13 | Data
6/2/13 | Data
7/1/13 | Data
9/1/13 | Data
我需要以某种方式获得创建节标题的月份,但前提是它们在数组中,然后将日期分解为适当的节。看起来像:
(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";
}
但是很明显,无论数组中有多少个月,都需要动态更新。日期实际上是数组中的NSDATE-如果这有什么区别的话。您需要转换现有的单个数组并创建一个新的字典数组。这个新数组中的每个字典将包含两个条目——一个用于月份,另一个条目将是一个数组,其中包含与月份关联的每一行的数据
如果需要在此结构中添加新行,请参见列表中已存在的月份。如果是,请更新当月的数组。否则,创建一个包含新月份的新字典和一个包含新行的新数组。我已经拼凑了一些至少应该编译的东西,但完全没有经过测试。基本上,这涉及到对数组进行预处理,并将结果存储在其他集合中,这些集合可以用作
UITableViewDataSource
的模型对象
将这些属性添加到作为数据源的类中。如果使用ARC,则必须以不同的方式声明它们
@property(retain) NSMutableArray* tableViewSections;
@property(retain) NSMutableDictionary* tableViewCells;
将此方法添加到数据源中,并确保在UITableView
调用第一个数据源方法之前的某个时间调用它重要:数组必须按排序顺序包含NSDate
对象(问题中的示例表明情况就是这样)
现在,在数据源方法中,您可以说:
- (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:
来更新tableviewssections
和tableviewscells
数组项的内容,它们是字符串、字典还是自定义对象?或者,您想对该做什么做一个冗长的描述吗?是的-您对正在排序的数组的假设是正确的。这正是我想要的,并且能够相应地修改代码。谢谢@user1453561让我知道当前的代码是否包含任何bug,我将相应地编辑答案,以便对其他人有用。如果您只需编辑内容以使其适应您的需要,则无需采取任何行动。我注意到的唯一一件事是“[self.tableViewCells setObject:tableViewCells forcement forKey:sectionHeading];”应该是[self.tableViewCells设置值:tableViewCells分区forKey:sectionHeading]代码>其他一切看起来都很好!
- (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];
}
[...]