我正在遵循一个简单的 iOS 7 教程并在表格 View 中使用标准字幕单元格类型,并获得了标题和副标题的两个标签。标签是:textLabel
和 detailTextLabel
我现在想自定义 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/