5

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.

Abhinav
  • 37,684
  • 43
  • 191
  • 309

2 Answers2

10
- (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
adriaan
  • 1,574
  • 14
  • 33
monowerker
  • 2,951
  • 1
  • 25
  • 23
  • The problem is string is not yet drawn on the screen. I am getting this data from server and for some functionality have to calculate in how many lines this will fit in a given size text area. Any solution around that? – Abhinav Apr 30 '11 at 01:51
  • I haven't checked this myself but the answer from Jano to this question http://stackoverflow.com/questions/5837348/counting-the-number-of-lines-in-a-textview-lines-wrapped-by-frame-size seems reasonable – monowerker Apr 30 '11 at 03:11
1

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).

Daniel Dickison
  • 21,832
  • 13
  • 69
  • 89