iOS 7 : Custom Style Cell in Tableview: How to reference labels?

标签 ios iphone objective-c uitableview

我正在遵循一个简单的 iOS 7 教程并在表格 View 中使用标准字幕单元格类型,并获得了标题和副标题的两个标签。标签是:textLabeldetailTextLabel
我现在想自定义 tableView 中的单元格,所以我将样式切换为自定义,并在 Storyboard 上创建了两个标签。然后,我将 IBOutlets 链接到我的 .m 文件的接口(interface)部分中的这些标签。它看起来像这样:

@interface MasterViewController ()

@property (weak, nonatomic) IBOutlet UILabel *textLabel;
@property (weak, nonatomic) IBOutlet UILabel *detailTextLabel;

@end

这就是我渲染单元格的代码的样子,我认为这是相当标准的。
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"KeyCell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

NSDictionary *key = [items objectAtIndex:indexPath.row];
NSString *name = [key objectForKey:@"name"];
NSString *type = [key objectForKey:@"type"];

cell.textLabel.text = name;
cell.detailTextLabel.text = [NSString stringWithFormat:@"Type : %@", type];    
return cell;
}

我做错了吗?

最佳答案

通过在您的 VC(您的委托(delegate))中创建一个 IBOutlet,您尝试链接这些 UILabel 的单个实例。

创建一个新的 UITableViewCell 子类并将您的原型(prototype)单元格设置为 IB 中的该类。然后将您的网点拖到该子类。这是使用网点的唯一方法。

不幸的是,我有点赶时间,否则我会发布一个完整的答案,但这里是如何做到的:
1.使用File->New->File... ;
2.选择 Cocoa Touch然后 Objective-C Class ;
3.输入类名并确保子类的类型为 UITableViewCell ;
4.单击下一步并在您选择的项目文件夹中创建类。
5.转到您的 Storyboard,单击您的原型(prototype)单元格;
6.在 Utilities(右侧) Pane 中,单击 Identity Inspector(第三个图标),然后在顶部的类条目中输入新类的名称。
7.像以前一样将 outlet 拖到 .m 文件中!

顺便说一句,使用 Storyboard和原型(prototype)单元意味着您的 if (cell == nil) { ...}部分现在是多余的,可以删除,因为 Storyboard保证返回一个单元格。

关于iOS 7 : Custom Style Cell in Tableview: How to reference labels?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22460681/

相关文章:

ios - 验证加密数据是否未被篡改

ios - 在 Swift 中 if let 赋值中 where 的用法

iphone - 在 Obj C 中使用 Brad Larson GPUImage 为照片创建素描效果

ios - 退出 iPhone 应用程序的正确方法?

objective-c - block 与委托(delegate)

objective-c - 在 Objective C 中将可变长度的 int 数组作为函数参数传递

ios - 可以让 titleView 接受点击手势吗?

ios - '@' token main.m之前的预期表达式

ios - 在 UITableView 中正确显示 JSON 数据

iphone - 当 App 已安装在设备上时,App Purchase 的 SKProductsRequest 不起作用