dequeueReusableCellWithIdentifier中的字幕

sta*_*s25 4 objective-c uitableview tableviewcell ios

我有这个代码

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;
Run Code Online (Sandbox Code Playgroud)

我不使用Interface Builder.我怎么能让这个单元格有副标题?我得到的只是标准细胞.

Rob*_*Rob 9

有两种方法:

  1. 旧式方法是不注册任何类,NIB或单元原型,dequeueReusableCellWithIdentifier不需要调用forIndexPath:

    - (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;
    }
    
    Run Code Online (Sandbox Code Playgroud)

    正如我们在别处讨论的那样,这假设您没有为该重用标识符注册一个类.

  2. 另一种方法是在以下位置注册您自己的课程viewDidLoad:

    [self.tableView registerClass:[MyCell class] forCellReuseIdentifier:@"Cell"];
    
    Run Code Online (Sandbox Code Playgroud)

    然后调用dequeueReusableCellWithIdentifier 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;
    }
    
    Run Code Online (Sandbox Code Playgroud)

    这显然假设您已经实现了UITableViewCell包含副标题的子类(注意我重写了样式):

    @interface MyCell : UITableViewCell
    @end
    
    @implementation MyCell
    
    - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
        return [super initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier];
    }
    
    @end
    
    Run Code Online (Sandbox Code Playgroud)

就个人而言,我认为设计一个单元原型(自动注册重用标识符并处理所有其他东西)要容易得多.即使是注册NIB的旧技术也比上述更容易.但是如果你想完全以编程方式完成它,那就是两种方法.