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.
For those of you who don't have a subclass of
UITableViewCell
:The code above sets the size to be 40x40.
Swift 2
Or you can use another(not tested) approach suggested by @Tommy:
Swift 3+
The code above is the Swift 3+ version of the above.
Here is @germanattanasio 's working method, written for Swift 3
I've created an extension using @GermanAttanasio 's answer. It provides a method to resize an image to a desired size, and another method to do the same while adding a transparent margin to the image (this can be useful for table views where you want the image to have a margin as well).
A Simply Swift,
Step 1: Create One SubClass of
UITableViewCell
Step 2: Add this method to SubClass of UITableViewCell
Step 3: Create cell object using that SubClass in
cellForRowAtIndexPath
,Step 4: Enjoy
Here's how i did it. This technique takes care of moving the text and detail text labels appropriately to the left: