Some times we need to customize our table cell’s height according to text length. For long text we need to make a bigger cell and vice versa. Here is the method to do this:
1. define you table cell’s size and font:
#define CONST_Cell_height 50.0f
#define CONST_Cell_width 270.0f
#define CONST_textLabelFontSize 16
#define CONST_detailLabelFontSize 14
2. Here is the method to calculate table cell width:
– (int) heightOfCellWithTitle :(NSString*)titleText
andSubtitle:(NSString*)subtitleText
{
CGSize titleSize = {0, 0};
CGSize subtitleSize = {0, 0};
if (titleText && ![titleText isEqualToString:@””])
titleSize = [titleText sizeWithFont:[UIFont boldSystemFontOfSize:16]
constrainedToSize:CGSizeMake(CONST_Cell_width, 4000)
lineBreakMode:UILineBreakModeWordWrap];
if (subtitleText && ![subtitleText isEqualToString:@””])
subtitleSize = [subtitleText sizeWithFont:[UIFont systemFontOfSize:14]
constrainedToSize:CGSizeMake(CONST_Cell_width, 4000)
lineBreakMode:UILineBreakModeWordWrap];
descriptionLabelHeight = subtitleSize.height;
return titleSize.height + subtitleSize.height;
}
3. Use this in your table height for row:
– (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *title = @”Yor cell title”;
NSString *subtitle =@”Your cell subtitle”;
int height = “some constant” + [self heightOfCellWithTitle:title andSubtitle:subtitle]; // some constant is used to adjust cell height. may be zero.
return (height < CONST_Cell_height ? CONST_Cell_height : height);
}
it will resize the table cell according to text size.
!! Enjoy !!