Proper Alignment of UIImage and UILabel when using UITableViewCellStyleSubtitle

less than 1 minute read

I am working on an iPhone App Project for a client and I decided to use the UITableViewCellStyleSubtitle for one of my views. It was easy to setup and it had all the details I needed. The only customization I did was change the detailTextLabel.numberOfLines to 2. So I loaded up my content and to my dismay, the cell is not intelligent enough to line up the labels horizontally across all cells. This really, really bothers me.

Before I set out to create my own class and draw my own labels and images, I thought I would just subclass UITableViewCell and try overriding the layouts for what I needed.

////////////////////////////
// .h file
#import <UIKit/UIKit.h>
@interface DemoTableViewCell : UITableViewCell {
}
@end
////////////////////////////
// .m file
#import "DemoTableViewCell.h"
#define MARGIN 10
@implementation DemoTableViewCell
- (void) layoutSubviews {
[super layoutSubviews];
CGRect cvf = self.contentView.frame;
self.imageView.frame = CGRectMake(0.0,
0.0,
cvf.size.height-1,
cvf.size.height-1);
self.imageView.contentMode = UIViewContentModeScaleAspectFit;
CGRect frame = CGRectMake(cvf.size.height + MARGIN,
self.textLabel.frame.origin.y,
cvf.size.width - cvf.size.height - 2*MARGIN,
self.textLabel.frame.size.height);
self.textLabel.frame = frame;
frame = CGRectMake(cvf.size.height + MARGIN,
self.detailTextLabel.frame.origin.y,
cvf.size.width - cvf.size.height - 2*MARGIN,
self.detailTextLabel.frame.size.height);
self.detailTextLabel.frame = frame;
}
@end
view raw gistfile1.m hosted with ❤ by GitHub


Turns out that was all I needed. After using this subclass instead of a UITableViewCell, I now get my image filling the square (if possible) and the Text Labels all lined up vertically.

This code makes 2 assumptions:

1) You want a square imageView that has a width equal to the height of the cell - 1 (for the separator)
2) You want the image to be aspect fit

Enjoy!

Was this page helpful for you? Buy me a slice of 🍕 to say thanks!

Comments