Dynamic multiline label with custom font in UITableViewController

Suppose you need to show long text in tableview cell with custom font then height is the major issue. See following steps to do this:
1. Download FontLabel app source from
It has a good library with sample to use custom fonts embedded with project. Add FontLabel library to your project.

2. See following to generate label with custom font dynamically.
#define CELL_CONTENT_WIDTH 320.0f

//Create Label with specific font, size and text on specific x,y.
- (FontLabel *)getLabel:(CGFloat)x :(CGFloat )y :(NSString *)fontName :(CGFloat )fontSize :(NSString *)text
 CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN+x), 20000.0f);
    CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:fontSize] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
 FontLabel *lbl =[[FontLabel alloc] initWithFrame:CGRectMake(x, y, CELL_CONTENT_WIDTH- (CELL_CONTENT_MARGIN+x), size.height)
            fontName:fontName pointSize:fontSize];
 lbl.textColor = [UIColor blackColor];
 lbl.text = text;
 lbl.numberOfLines = 0;
 //lbl.textAlignment = UITextAlignmentLeft;
 lbl.lineBreakMode = UILineBreakModeWordWrap;
 lbl.baselineAdjustment = UIBaselineAdjustmentNone;  
 [lbl sizeToFit];
 return lbl;
3.You can add labels in tableview cell using cellForRowAtIndexPath method

lblID = [self getLabel:CELL_CONTENT_MARGIN :CELL_CONTENT_MARGIN :@"angelina" :24.0f :title];
[cell addSubview: lblID];

4. We need to set tableview cell height according to multiline label height. See following for this:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
 FontLabel *lbl = [[self getLabelFromIndex:indexPath] retain];
 CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
    CGSize size = [lbl.text sizeWithFont:lbl.font constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
    CGFloat height = size.height;
    return height + (CELL_CONTENT_MARGIN * 2);
where getLabelFromIndex returns label of the cell.

Hope, It helps.

No comments:

Post a Comment