0

我有一个需要UITableView在部分中显示的数组。

我目前在一个部分下按日期顺序显示对象,但我需要按年份对它们进行部分,我不知道如何去做。

我的对象是...

@interface MyEvent : NSObject

@property NSDate *date;
@property NSString *title;
@property NSString *detail;

@end

我的数组是按日期顺序排列的这些对象的数组。

我可以直接从这个数组中执行此操作,还是需要将数组分成二维数组。

即 NSArray 的 NSArray,其中第二个 NSArray 中的每个对象都在同一年。

4

2 回答 2

1

您可以从下面显示的链接中获得帮助:

UITableView 节标题按数组中的日期月份

http://oleb.net/blog/2011/12/tutorial-how-to-sort-and-group-uitableview-by-date/

于 2013-10-15T12:50:42.770 回答
1

TLIndexPathDataModel使用TLIndexPathTools作为数据结构很容易做到这一点。基于块的初始化程序提供了将数据组织成部分的几种方法之一:

NSArray *sortedEvents = ...; // events sorted by date
TLIndexPathDataModel *dataModel = [[TLIndexPathDataModel alloc] initWithItems:sortedEvents sectionNameBlock:^NSString *(id item) {
    MyEvent *event = (MyEvent *)item;
    NSString *year = ...; // calculate section name for the given item from date
    return year;
} identifierBlock:nil];

然后使用数据模型 API,数据源方法变得非常简单:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataModel.numberOfSections;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataModel numberOfRowsInSection:section];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellId = ...;
    UITableViewCell *cell = ...; // dequeue cell
    MyEvent *event = [self.dataModel itemAtIndexPath:indexPath];
    ... // configure cell
    return cell;
}
于 2013-10-15T14:49:47.780 回答