如何加载表格单元格?以下是json数据

时间:2016-04-16 18:26:33

标签: ios json swift uitableview

[{
    "firstName": "John",
    "lastName": "Doe"
}, {
    "firstName": "Anna",
    "lastName": "Smith"
}, {
    "firstName": "Peter",
    "lastName": "Jones"
}]

我有这些类型的json数据,如何加载表格单元格,加载名字和姓氏的关键值是什么?

2 个答案:

答案 0 :(得分:2)

Swift版

 //create a struct to represent your data
 struct People {
     var firstName: String!
     var lastName: String!
 }

 //create an array to store your data in your class
 var peopleArray: [People]?

 //when the view loads, take the data you receive and parse it
 for person in dataReceived {
     let personToAdd = People(firstName: person["firstName"], lastName: person["lastName"]
     peopleArray.append(personToAdd)
 }

 //cell for row at index path
 let cell = tableView.dequeueReusableCellWithIdentifier("identifier")
 let personForCell = peopleArray[indexPath.row]
 cell.textLabel!.text = personForCell.firstName
 cell.detailTextLabel.text = personForCell.lastName

答案 1 :(得分:0)

@property (nonatomic, strong) NSArray *responseArray;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // get JSON response from server or local to NSArray
    _responseArray = [NSJSONSerialization JSONObjectWithData:yourJsonHere options:0 error:nil];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cellIdentifier"];

    NSDictionary *row = _responseArray[indexPath.row];
    [cell.textLabel setText:row[@"firstName"]];
    [cell.detailTextLabel setText:row[@"lastName"]];
    return cell;
}

相应地更改UITableViewCellStyle或为其创建自己的标签。