如何为NSArray添加字幕

时间:2012-12-16 17:12:52

标签: ios objective-c uitableview

我正在努力寻找一种更好的方法来添加字幕目前有两个不同的数组我想知道你是否可以在与标题相同的数组中添加字幕?

lodgeList = [[NSArray alloc]initWithObjects:

             //Abingdon
             @"Abingdon Lodge No. 48",  // This is the Title 
             // I would like to add the subtitle here

             @"York Lodge No. 12",

             //Alberene
             @"Alberene Lodge No. 277",

             // Alexandria
             @"A. Douglas Smith, Jr. No. 1949",
             @"Alexandria-Washington Lodge No. 22",
             @"Andrew Jackson Lodge No. 120",
             @"Henry Knox Field Lodge No. 349",
             @"John Blair Lodge No. 187",
             @"Mount Vernon Lodge No. 219",

如何为上面的每个名称添加字幕?

1 个答案:

答案 0 :(得分:6)

创建一个类,它具有标题和副标题的NSString属性。实例化对象。投入阵列。

-(UITableViewCell *)tableView:(UITableView *)tableview cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     //…
    MyLodge *lodge = lodgeList[indexPath.row];
    cell.textLabel.text = lodge.title;
    cell.detailLabel.text = lodge.subtitle;
    return cell;
}

而不是自定义类,您也可以使用NSDictionaries。

lodgeList = @[ 
                @{@"title":@"Abingdon Lodge No. 48",
                  @"subtitle": @"a dream of a lodge"},
                @{@"title":@"A. Douglas Smith, Jr. No. 194",
                  @"subtitle": @"Smith's logde…"},
             ];

此代码以new literal syntax

为特色
-(UITableViewCell *)tableView:(UITableView *)tableview cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     //…
    NSDictionary *lodge = lodgeList[indexPath.row];
    cell.textLabel.text = [lodge objectForKey:@"title"];
    cell.detailLabel.text = [lodge objectForKey:@"subtitle"];
    return cell;
}

实际上,对于两种解决方案,您可以使用tableView:cellForRowAtIndexPath: -(UITableViewCell *)tableView:(UITableView *)tableview cellForRowAtIndexPath:(NSIndexPath *)indexPath { //… id lodge = lodgeList[indexPath.row]; cell.textLabel.text = [lodge valueForKey:@"title"]; cell.detailLabel.text = [lodge valueForKey:@"subtitle"]; return cell; } 相同的实现:

{{1}}

  

这适用于原型细胞吗?

是的,如Key-Value-Coding所示,您将创建UITableViewCell的子类,为其提供一个属性来保存您的模型和属性以反映标签。这些标签将在故事板中连线