我如何实现`prepareForReuse`?

use*_*509 7 objective-c uitableview ios

我正在设置一个用sdwebimage下载的图像UITableViewCell.为了,为了保持UITableView从显示错误的图像,我需要将图像设置为nilprepareForReuse.但是,我在实现这个方面遇到了一些麻烦.

这是我设置图像的地方:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * reuseIdentifier = @"programmaticCell";
    MGSwipeTableCell * cell = [self.tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[MGSwipeTableCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier];
    }

    CGFloat brightness = [UIScreen mainScreen].brightness;

    cell.textLabel.text = [self.streams[indexPath.row] name];
    cell.detailTextLabel.text = [self.streams[indexPath.row] published];

    NSString *imageUrl = [NSString stringWithFormat: @"%@", [self.streams[indexPath.row] photo]];

    NSLog(@"Image is: %@ and path is: %d", imageUrl, indexPath.row);

    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:imageUrl]
                      placeholderImage:[UIImage imageNamed:@"tile-blue.png"] options:indexPath.row == 0 ? SDWebImageRefreshCached : 0];

    cell.delegate = self; //optional

    return cell;
}
Run Code Online (Sandbox Code Playgroud)

当我实现- (void)prepareForSegueXcode不断抛出错误,说它cell不可用.实现这个的正确方法是什么?

Mik*_*rne 9

尝试将此添加到您的MGSwipeTableCell.m:

-(void)prepareForReuse
{
    [super prepareForReuse];

    self.textLabel.text = @"";
    self.detailTextLabel.text = @"";
    self.imageView.image = nil;
} 
Run Code Online (Sandbox Code Playgroud)

  • 作为对上述解决方案的评论,Mike可能知道(仅仅是演示代码):不要实现prepareForReuse来重置单元格的内容.它应该只重置外观.来自文档:"出于性能原因,您应该只重置与内容无关的单元格属性,例如,alpha,编辑和选择状态." 进一步说:"tableView中的表视图委托:cellForRowAtIndexPath:应该在重用单元格时重置所有内容".在cellForRowAtIndexPath中设置文本内容,重置```prepareForReuse```中的外观. (8认同)
  • 非常欢迎你!不久前我偶然发现了这件事.在尝试从UITableView中获得最佳性能时,请记住这一点. (3认同)