Jim
Jim

Reputation: 9234

iPhone: Text width in pixels

I have UILabel (286, 50). When I set some text with font Helvetica 16, label divides text on 2 rows. Thats grate. Now I want to get this text width in pixels.

CGSize uiLabelSize = CGSizeMake(286, 50);
return [text sizeWithFont:[UIFont fontWithName:@"Helvetica" size:16]
    constrainedToSize:uiLabelSize lineBreakMode:UILineBreakModeWordWrap].width;

But looks like this method dont want to divide this text on 2 rows. it returns for me 284 px.

Any idea how to be ?

 return [text sizeWithFont:[UIFont
    fontWithName:@"Helvetica" size:16]].width;

This method not work for me. Because if in first row last word is too long, than UILineBreakModeWordWrap will move last word on second row...

Sorry for hard explanation, let me know if I need to be more clear...

Upvotes: 0

Views: 1222

Answers (3)

Jano
Jano

Reputation: 63667

Replace 50 with an unconstrained height:

CGSize textSize = [text sizeWithFont:font 
                   constrainedToSize:CGSizeMake(286.0, FLT_MAX) 
                       lineBreakMode:UILineBreakModeWordWrap];

edit:

NSString *text = @"what's wrong with your hair? it's like a science experiment back there. Don't rub more salt in the wound.";
UIFont *font = [UIFont fontWithName:@"Helvetica" size:16];
CGSize textSize = [text sizeWithFont:font 
                   constrainedToSize:CGSizeMake(286.0, FLT_MAX) 
                       lineBreakMode:UILineBreakModeWordWrap];
NSLog(@"%f,%f", textSize.width,textSize.height);

This outputs 272 width (because it is word wrapping before 286 pixels) and 60 height (because it is taking two lines).

Upvotes: 1

Frade
Frade

Reputation: 2988

Try something llike this:

CGSize labelSize = [label.text sizeWithFont:label.font constrainedToSize:label.frame.size lineBreakMode:label.lineBreakMode];

labelSize gets the size of label constrained by text

I'm not sure if it is what you need..

Upvotes: 0

Kjuly
Kjuly

Reputation: 35131

UILabel * testLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 286.0f, 50.0f)];
[testLabel setText:@"ab"];
NSLog(@"%f",[testLabel.text sizeWithFont:[UIFont fontWithName:@"Helvetica" size:16] constrainedToSize:CGSizeMake(286.0f, 50.0f) lineBreakMode:UILineBreakModeWordWrap].width);

It looks interesting. So I tried in my xcode and the code above works for me. When set text to @"a", the width returns 9, and @"ab" returns 18.
Have you set the text? Or you may mix the UILabel with its text?
I'm not sure this is that you want, just give some tips.

Upvotes: 0

Related Questions