- (void)setDefaultRowHeights
{
self.imageHeights = [NSMutableArray arrayWithCapacity:self.imageURLs.count];
for (int i = 0; i < self.imageURLs.count; i++) {
self.imageHeights[i] = @(self.tableView.rowHeight);
}
}
- (void)setDefaultRowHeights {
self.imageHeights = [NSMutableArray arrayWithCapacity:self.imageURLs.count];
for (int i = 0; i < self.imageURLs.count; i++) {
self.imageHeights[i] = @(self.tableView.rowHeight);
}
}
然后,让我们转到 tableView:cellForRowAtIndexPath: 下载图像并将它们的高度存储在我们的 imageHeights 数组中(这是一个很长的数组,但不要害怕)。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
DynamicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DynamicCell" forIndexPath:indexPath];
NSString *imageURL = self.imageURLs[indexPath.row];
__weak DynamicTableViewCell *weakCell = cell;
__weak typeof(self) weakSelf = self;
[cell.mainImageView setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:imageURL]]
placeholderImage:[UIImage new]
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
weakCell.mainImageView.image = image;
// Update table row heights
NSInteger oldHeight = [weakSelf.imageHeights[indexPath.row] integerValue];
NSInteger newHeight = (int)image.size.height;
// If image is wider than our imageView, calculate the max height possible
if (image.size.width > CGRectGetWidth(weakCell.mainImageView.bounds)) {
CGFloat ratio = image.size.height / image.size.width;
newHeight = CGRectGetWidth(self.view.bounds) * ratio;
}
// Update table row height if image is in different size
if (oldHeight != newHeight) {
weakSelf.imageHeights[indexPath.row] = @(newHeight);
[weakSelf.tableView beginUpdates];
[weakSelf.tableView endUpdates];
}
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(@"Error: %@\nFetching image with url: %@", error, request.URL);
}];
return cell;
}
简单!我们现在可以在 tableView:heightForRowAtIndexPath: 方法中返回正确的值,如下所示:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return [self.imageHeights[indexPath.row] integerValue];
}
正确重新加载表格视图单元格
尝试尝试几种不同的方法。我发现当单元格高度改变时,只调用 beginUpdates 和 endUpdates 会产生最好的动画/过渡。您也可以在这两者之间调用 reloadRowsAtIndexPaths:withRowAnimation: 但它会进行额外的刷新并且 UI 看起来很糟糕。