objective-c - iOS UITableView : Custom sections using information from a JSON object, 不只是计算它

标签 objective-c ios json uitableview sections

假设我有这个 JSON:

[
    {"x":"01", "ID":"1"},
    {"x":"02", "ID":"2"},
    {"x":"02", "ID":"3"},
    {"x":"03", "ID":"4"},
    {"x":"03", "ID":"5"},
    {"x":"03", "ID":"6"},
    {"x":"03", "ID":"7"}
]

我想像这样创建一个 UITableView:

------------
Section 01
------------
ID: 1
------------
Section 02
------------
ID: 2
ID: 3
------------
Section 03
------------
ID: 4
ID: 5
ID: 6
ID: 7

如何找出我需要多少个部分以及如何在每个部分中输出正确的数据?

最佳答案

首先要做的是将该 JSON 转换为 Objective-C 数据结构。我推荐一个数组数组,其中“X”是每个“ID”值数组的索引。

类似于:

NSMutableArray *tableSections;
NSMutableArray *sectionData;

CustomDataObject *yourCustomDataObject;

int sectionIndex;

//Pseudo-code to create data structure
for(data in json) {

    sectionIndex = data.X;

    yourCustomDataObject = [[CustomDataObject alloc] initWithId:data.ID];

    //Do index check first to insure no out of bounds
    if(sectionIndex != OutOfBounds)
        sectionData = [tableSections objectAtIndex:sectionIndex];

    //Create the new section array if there isn't one for the current section
    if(!sectionData) {
        sectionData = [NSMutableArray new];
        [tableSections insertObject: sectionData atIndex: sectionIndex];
        [sectionData release];
    }

    [sectionData addObject: yourCustomDataObject];
    [yourCustomDataObject release];
}

上面的代码只是帮助您入门的伪代码。创建这个数组数组可能是您之前已经做过的事情。

重要的部分是通过实现 UITableViewDataSource 协议(protocol)来访问这些数据。我建议继承 UITableView 并在自定义子类中实现 UITableViewDataSource 协议(protocol)。

您将需要这些方法:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [tableSections count];
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[tableSections objectAtIndex: section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    //Implement as you normally would using the data structure you created

    NSMutableArray *sectionData = [tableSections objectAtIndex: indexPath.section];
    CustomDataObject *dataObject = [sectionData objectAtIndex: indexPath.row];

    NSLog(@"\n**** Debug Me *****indexPath: section: %i row: %i \ndataObject%@", indexPath.section, indexPath.row, dataObject);
}

这应该足以让您入门。弄清楚其余的细节应该是一种很好的做法。

关于objective-c - iOS UITableView : Custom sections using information from a JSON object, 不只是计算它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13943285/

相关文章:

iphone - 切换两个 UISwitch

ios - 当从 iphone 上的 push segue 导航回来时,顶部导航栏变得可见

ios - 如何对齐 UITextField 中的文本?

ios - 如何使用本地设备 Facebook 登录 Meteor?

ios - 图像大小优化以减少数据使用

iphone - 使用 NSJSONSerialization 将 NSMutableDictionary 转换为 JSON 返回不同的结果

ios - 推送通知传递和关闭回调

iphone - xcode 4.2项目在iPhone上运行|真实设备

javascript - 循环遍历json对象来创建jquery表

json - 在 Moment.js 中检查日期是否大于 0001-01-01