Search code examples
objective-cios6

In UILabel how to multiline text with custom width


My UILabel is in UITableViewCell and Here is my code

lblgoal = [[UILabel alloc] initWithFrame:CGRectMake(60,10, 250, 20)];
CGSize maximumLabelSize1 = CGSizeMake(230,9999);
            lblgoal.numberOfLines = 0;
            lblgoal.adjustsFontSizeToFitWidth = NO;
            CGSize expectedLabelSize = [sg.subgoal_name sizeWithFont:lblgoal.font
                                                   constrainedToSize:maximumLabelSize
                                                   lineBreakMode:lblsubgoal1.lineBreakMode];
CGRect newFrame = lblgoal.frame;
            newFrame.size.height = expectedLabelSize.height;
            lblgoal.frame = newFrame;

But this only works if i put the width of UILabel to 200, if i put more than 200 width, then it all comes in one line with dotted at the end. And, UITableView cell width is more than 500.


Solution

  • Actually, make sure to set the linebreakmode to UILineBreakModeWordWrap in both your sizeWithFont function and your lblgoal label as below:

    lblgoal.numberOfLines = 0;
    lblgoal.lineBreakMode = UILineBreakModeWordWrap; //NSLineBreakByWordWrapping for iOS 6
    

    EDIT: Try sizeToFit after you set the lineBreakMode.

    [lblgoal sizeToFit];
    

    Also make sure you do this inside the cellForRowAtIndexPath method.

    You should also implement the following delegate method to make sure the height of your cell is also adjusted accordingly.

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath