Stefan Olaru
Stefan Olaru

Reputation: 63

UILabel Text Multi Line given width of text

I want to scale a UILabel exactly how snapchat does. I have a textfield where I insert the text. When tapping done the textfield goes and the label's text is set. I want to insert multiple lines when the text is larger than width of screen and truncate the frame of label so that the text fits.

Here is my code

if(isCaption){
    //Begin Edit Text
    _textlabel.hidden = NO;
    _textlabel.text = currentText;
    _textFieldOutlet.hidden = YES;
    [_textFieldOutlet setTextAlignment:NSTextAlignmentLeft];
    [_textlabel setTextAlignment:NSTextAlignmentLeft];
    [self.screenShotView bringSubviewToFront:_textlabel];

    _textlabel.frame = CGRectMake(10,
                                  _textlabel.frame.origin.y,
                                  [currentText sizeWithAttributes:@{NSFontAttributeName:[_textlabel font]}].width,
                                  [currentText sizeWithAttributes:@{NSFontAttributeName:[_textlabel font]}].height);


    isEditing = YES;
    isCaption = NO;


}

The problem is that the result is a huge line of text and I want it spreads on multiline. How can this be accomplished? How can I separate the lines given width?

Upvotes: 0

Views: 432

Answers (2)

Jaycee
Jaycee

Reputation: 159

If you want multiple lines you should not calculate your width with sizeWithAttributes: . You should fix your width for the label and then calculate the height with boundingRectWithSize: method.

You can create a helper method as follows:

- (CGSize)suggestedSizeWithFont:(UIFont *)font size:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode forString:(NSString *)text {
      NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
      paragraphStyle.lineBreakMode = lineBreakMode;
      NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName: font,       NSParagraphStyleAttributeName: paragraphStyle}];
      CGRect bounds = [attributedString boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin context:nil];
      return bounds.size;
}

Or you can create a category and get rid of that extra text parameter.

Then you can call the method for you label's text as follows:

CGSize requiredSize = [self suggestedSizeWithFont:_textLabel.font size:CGSizeMake(self.view.frame.size.width, CGFLOAT_MAX) lineBreakMode:_textLabel.lineBreakMode forString:_textLabel.text];
_textLabel.frame = CGRectMake(0, _textlabel.frame.origin.y, requiredSize.width, requiredSize.height);

You can set the width to whatever you want your label to fit in. The height would calculated accordingly. But remember to set numberOfLines to 0.

Upvotes: 2

Jaycee
Jaycee

Reputation: 159

Try to insert following line of code:

_textLabel.numberOfLines = 0;

Upvotes: 0

Related Questions