【问题标题】:Creating sections for years from array of dates从日期数组创建多年的部分
【发布时间】:2013-10-15 12:42:49
【问题描述】:

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

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

我的对象类似于...

@interface MyEvent : NSObject

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

@end

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

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

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

【问题讨论】:

    标签: ios objective-c uitableview


    【解决方案1】:
    【解决方案2】:

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

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-10-10
      • 1970-01-01
      • 2013-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-07
      • 2011-04-26
      • 1970-01-01
      相关资源
      最近更新 更多