I encountered an annoying issue in my app so I made a demo for this for convenience:
There are two UIViewControllers A & B. B is pushed from the A and contains an UITableView which is using self-sizing cell. In the UITableViewCell there is an UIImageView which set its top, leading, bottom and trailing constraint to the cell. So when the image of that ImageView is set, cell height will be auto determined.
However, when the B is pushed the first time and update its content, the cell height is not correct. But if pop B then push B again, the cell height will be correct.
So in my app, each scene like B can not get the right cell size if not be pushed the second time.
Related code is as below. The whole demo can be found in 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
You should update the table, not the cell. The table view has some feature, that just updates the row heights. Just call this methods one after another:
[tableView beginUpdates];
[tableView endUpdates];