iOS: UIImageView changes with change in UITableView.rowHeight, how to avoid?

爱⌒轻易说出口 提交于 2019-12-04 21:17:00

The problem is that you are using a default table view cell style. That style comes with a built-in textLabel and an imageView, and the latter is a UIImageView with constraints so that it is resized to fill the height of the cell. But you have also said

 cell.imageView.contentMode = UIViewContentModeScaleAspectFit

Which means that as the image view grows, the image grows with it - exactly what you are seeing.

The solution, as I explain here, is to size the image down to the actual size that you want it - and set the image view's contentMode to center. Something like this:

UIImage* im = [self getImageNameForRow:indexPath.row];
UIGraphicsBeginImageContextWithOptions(CGSizeMake(36,36), YES, 0);
[im drawInRect:CGRectMake(0,0,36,36)];
UIImage* im2 = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
cell.imageView.image = im2;
cell.imageView.contentMode = UIViewContentModeCenter;

Change that 36,36 to the size you actually want.

This is good practice anyway. It is a terrible waste of memory to hold onto an image at a larger size than needed for actual display (the amount of wasted memory grows exponentially, because area is on the order of the square of a single dimension). So you should always size images down to their actual display size. There's lots and lots of code on Stack Overflow showing many other ways to do that.

I believe your main problem here is the image is too large. If the image were only 40x40, it would appear as half the tableViewCell's height (when it's 80). IIRC the UIImageView in that UITableViewCell stretches to the height of the cell, and images will always fill it if they're large enough.

Three things you could do:

1) Shrink the size of the image to the size you want.

2) Change the frame of the imageView manually like so:

cell.imageView.image = [self getImageNameForRow:indexPath.row];
CGPoint center = cell.imageView.center;
CGRect frame = cell.imageView.frame;
frame.size.width = 40;
frame.size.height = 40;
cell.imageView.frame = frame;
cell.imageView.center = center;

I'm not entirely certain if you need to cache the center and re-set it after the frame change or not (the UITableViewCell might do this automatically).

3) Make a custom UITableViewCell subclass that has a fixed size UIImageView. I've detailed how to do this on my blog here.

I recommend 1 or 3.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!