How do I make UITableViewCell's ImageView a fixed size even when the image is smaller

I have a bunch of images I am using for cell's image views, they are all no bigger than 50x50. e.g. 40x50, 50x32, 20x37 .....

When I load the table view, the text doesn't line up because the width of the images varies. Also I would like small images to appear in the centre as opposed to on the left.

Here is the code I am trying inside my 'cellForRowAtIndexPath' method

cell.imageView.autoresizingMask = ( UIViewAutoresizingNone );
cell.imageView.autoresizesSubviews = NO;
cell.imageView.contentMode = UIViewContentModeCenter;
cell.imageView.bounds = CGRectMake(0, 0, 50, 50);
cell.imageView.frame = CGRectMake(0, 0, 50, 50);
cell.imageView.image = [UIImage imageWithData: imageData];

As you can see I have tried a few things, but none of them work.


Solution 1:

It's not necessary to rewrite everything. I recommend doing this instead:

Post this inside your .m file of your custom cell.

- (void)layoutSubviews {
    [super layoutSubviews];
    self.imageView.frame = CGRectMake(0,0,32,32);
}

This should do the trick nicely. :]

Solution 2:

For those of you who don't have a subclass of UITableViewCell:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 [...]

      CGSize itemSize = CGSizeMake(40, 40);
      UIGraphicsBeginImageContextWithOptions(itemSize, NO, UIScreen.mainScreen.scale);
      CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
      [cell.imageView.image drawInRect:imageRect];
      cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
      UIGraphicsEndImageContext();

 [...]
     return cell;
}

The code above sets the size to be 40x40.

Swift 2

    let itemSize = CGSizeMake(25, 25);
    UIGraphicsBeginImageContextWithOptions(itemSize, false, UIScreen.mainScreen().scale);
    let imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
    cell.imageView?.image!.drawInRect(imageRect)
    cell.imageView?.image! = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

Or you can use another(not tested) approach suggested by @Tommy:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 [...]

      CGSize itemSize = CGSizeMake(40, 40);
      UIGraphicsBeginImageContextWithOptions(itemSize, NO, 0.0)          
 [...]
     return cell;
}

Swift 3+

let itemSize = CGSize.init(width: 25, height: 25)
UIGraphicsBeginImageContextWithOptions(itemSize, false, UIScreen.main.scale);
let imageRect = CGRect.init(origin: CGPoint.zero, size: itemSize)
cell?.imageView?.image!.draw(in: imageRect)
cell?.imageView?.image! = UIGraphicsGetImageFromCurrentImageContext()!;
UIGraphicsEndImageContext();

The code above is the Swift 3+ version of the above.