views:

36

answers:

1

Hey,

I'm trying to calculate the height of the text constrained by a UITextView but it doesn't seem to return correct results.

Here is my code :

- (void)textViewDidChange:(UITextView *)aTextView {
    CGSize textSize = [aTextView.text sizeWithFont:aTextView.font constrainedToSize:aTextView.frame.size lineBreakMode:UILineBreakModeWordWrap];
    counter.text = [NSString stringWithFormat:@"%f", textSize.height];
}

You can download the sample project and a short screencast that illustrates the problem (418 KB).

In summary, the problem is that when I type a long word at the end of a line, the word is moved to the next line, but the height of the string isn't correctly adjusted when it happens.

Any help appreciated.

Best,
Thomas.

P.S. : It happens with the iPhone SDK 3.1.3

+1  A: 

The issue is that the UITextField has a slight margin around the area it actually draws and wraps the text. As far as I know there is no programatic way to get this size, but just subtracting 6 or so from the size should make it behave appropriately.

Joshua Weinberg
Thanks for your answer.My guess is indeed that the UITextView has some kind of padding.I would have liked to have a clean way to determine its size.In my example, substracting 11 to the textView width and height does the trick.
Thomas Balthazar
Like this : : - (void)textViewDidChange:(UITextView *)aTextView { CGSize textViewSize = aTextView.frame.size; textViewSize.width-= kTextViewPadding; textViewSize.height-= kTextViewPadding; CGSize textSize = [aTextView.text sizeWithFont:aTextView.font constrainedToSize:textViewSize lineBreakMode:UILineBreakModeWordWrap]; counter.text = [NSString stringWithFormat:@"%f", textSize.height]; }
Thomas Balthazar
I'd say file a radar, and for the time being use a hardcoded value.Glad you figured it out
Joshua Weinberg