Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the correct width of a NSString

On what factors does the wrapping of the text inside a textview depends. Width of my textview is 160 px and I calculated the width of the incoming text using below mentioned code and it comes out to be 157 px but this text is wrapped in 3 lines... Why so?

CGSize size = [myText sizeWithFont:textViewFont 
            constrainedToSize:textView.frame.size 
            lineBreakMode:UILineBreakModeWordWrap];

CGFloat textWidth = size.width;

I thought of dividing width of text with width of the textview to get the number of lines. But calculation returns me 1 whereas I can see 3 lines coming in textview on simulator.

like image 796
Abhinav Avatar asked Apr 29 '11 23:04

Abhinav


2 Answers

- (CGSize)sizeWithFont:(UIFont *)font
     constrainedToSize:(CGSize)size
         lineBreakMode:(UILineBreakMode)lineBreakMode

Calculates the size for a string if it would be drawn constrained by the size given as an argument, if the string is too long for the given size constraint it will get truncated to fit.

To get the width of the string if it's drawn on a single line with no constraints use:

- (CGSize)sizeWithFont:(UIFont *)font

see: http://developer.apple.com/library/ios/#documentation/uikit/reference/NSString_UIKit_Additions/Reference/Reference.html

NOTE: As of iOS7

- (CGSize)sizeWithFont:(UIFont *)font

is deprecated, instead use:

- (CGSize)sizeWithAttributes:(NSDictionary *)attrs
like image 186
monowerker Avatar answered Nov 15 '22 02:11

monowerker


Try setting the height of the size you pass into that method to be something huge. Otherwise the returned size will always show the actual height of the text view (assuming the full string does not fit in the given height).

like image 43
Daniel Dickison Avatar answered Nov 15 '22 03:11

Daniel Dickison