How to group an NSMutableArray and show in UITableView?

旧巷老猫 提交于 2019-12-06 10:00:41

You can roll your own data structures for this, but the TLIndexPathTools library automatically sections your table when you specify a sectionNameKeyPath, which in this case is just going to be "datetime". I put a working example with your data up on GitHub. Try running the JSON example project. The full source of the view controller is as follows:

#import "TLTableViewController.h"

@interface JSONTableViewController : TLTableViewController
@end

#import "JSONTableViewController.h"
#import "TLIndexPathDataModel.h"

@implementation JSONTableViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    //simulated JSON response as an array of dictionaries
    NSArray *jsonData = @[
        @{
            @"id": @(58),
            @"title": @"title59",
            @"summary": @"summary59",
            @"datetime": @"2013.02.03",
        },
        @{
            @"id": @(57),
            @"title": @"title58",
            @"summary": @"summary58",
            @"datetime": @"2013.02.04",
        },
        @{
            @"id": @(56),
            @"title": @"title57",
            @"summary": @"summary57",
            @"datetime": @"2013.02.04",
        },
        @{
            @"id": @(55),
            @"title": @"title56",
            @"summary": @"summary56",
            @"datetime": @"2013.02.05",
        }
    ];

    //initialize index path controller with a data model containing JSON data.
    //using "datetime" as the `sectionNameKeyPath` automatically groups items
    //by "datetime".
    self.indexPathController.dataModel = [[TLIndexPathDataModel alloc] initWithItems:jsonData
                                                            andSectionNameKeyPath:@"datetime"
                                                             andIdentifierKeyPath:@"id"];
}

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dict = [self.indexPathController.dataModel itemAtIndexPath:indexPath];
    cell.textLabel.text = dict[@"title"];
    cell.detailTextLabel.text = dict[@"summary"];
}

@end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!