当第一次设置里面的 imageView 时,自调整单元格没有更新它的高度

Self-sizing cell did not updated its height when the imageView inside it was set the first time

我在我的应用程序中遇到了一个烦人的问题,所以为了方便起见我做了一个演示:

有两个 UIViewControllerA 和 B。B 是从 A 推出的,包含一个 UITableView,它使用自调整大小细胞。在 UITableViewCell 中有一个 UIImageView 将其顶部、前导、底部和尾部约束设置为单元格。所以当ImageView的图像被设置时,单元格高度将被自动确定。

但是,当第一次推送B并更新其内容时,单元格高度不正确。但是如果pop B然后再push B,单元格高度就会正确。

所以在我的应用中,像B这样的每个场景如果不被第二次推送就无法获得正确的单元格大小。

相关代码如下。整个演示可以在 Github

中找到
#import "AnotherViewController.h"
#import "UIImageView+WebCache.h"
#import "UIImage+Ex.h"
#import "CustomCell.h"

static NSString * const kImageUrl = @"http://img02.tooopen.com/images/20151228/tooopen_sy_152967398112.jpg";

@implementation AnotherViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.estimatedRowHeight = 300;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    __weak typeof(CustomCell) *wCell = cell;
    [cell.bigImageView sd_setImageWithURL:[NSURL URLWithString:kImageUrl] placeholderImage:[UIImage imageNamed:@"default_cover"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        UIImage *scaledImage = [UIImage gs_scaledImageWithWidth:[UIApplication sharedApplication].keyWindow.bounds.size.width image:image];
        wCell.bigImageView.image = scaledImage;
        [wCell setNeedsUpdateConstraints];
    }];
    return cell;
}

@end

您应该更新 table,而不是单元格。 table 视图有一些功能,它只更新行高。 只需依次调用此方法即可:

[tableView beginUpdates];
[tableView endUpdates];