我有这个代码
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
Song *song = [self.music objectAtIndex:indexPath.row];
cell.textLabel.text = song.title;
cell.detailTextLabel.text = song.artist;
return cell;
我不使用 Interface Builder。我怎样才能让这个单元格有字幕?我得到的只是一个标准单元格。
最佳答案
有两种方法:
旧式方法是不注册任何类、NIB 或单元格原型(prototype),在没有 forIndexPath 的情况下调用 dequeueReusableCellWithIdentifier:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Cell"];
}
Song *song = self.music[indexPath.row];
cell.textLabel.text = song.title;
cell.detailTextLabel.text = song.artist;
return cell;
}
正如我们在别处讨论的那样,这假设您没有为该重用标识符注册一个类。
另一种方法是在 viewDidLoad 中注册您自己的类:
[self.tableView registerClass:[MyCell class] forCellReuseIdentifier:@"Cell"];
然后调用dequeueReusableCellWithIdentifier with forIndexPath 选项,但是如果是nil 就失去了手动测试的代码(因为它永远不会是 nil):
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
Song *song = self.music[indexPath.row];
cell.textLabel.text = song.title;
cell.detailTextLabel.text = song.artist;
NSLog(@"title=%@; artist=%@", song.title, song.artist); // for diagnostic reasons, make sure both are not nil
return cell;
}
这显然假设您已经实现了一个包含副标题的 UITableViewCell 子类(注意我正在覆盖样式):
@interface MyCell : UITableViewCell
@end
@implementation MyCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
return [super initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier];
}
@end
就我个人而言,我认为设计一个单元格原型(prototype)(自动注册重用标识符并处理所有其他事情)要容易得多。即使是注册 NIB 的旧技术也比上面的更容易。但如果您想完全以编程方式完成,这就是这两种方法。
关于ios - dequeueReusableCellWithIdentifier 中的副标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31989103/