Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does NSString sizeWithFont: return the wrong size?

I need to work out the height of a UITextView from the top down to the cursor. I am trimming the text it contains (so it only goes up to the cursor) and then using NSString's sizeWithFont:constrainedToSize:lineBreakMode: method to work out the height, like so:

   NSRange range;
   range.location = noteTextView.selectedRange.location;
   range.length = noteTextView.text.length - range.location;

   NSString *string = [noteTextView.text stringByReplacingCharactersInRange:range withString:@""];

   CGSize size = [string sizeWithFont:noteTextView.font 
                     constrainedToSize:noteTextView.frame.size 
                         lineBreakMode:UILineBreakModeWordWrap];

   NSLog(@"height is: %f \n", size.height);

It does this every time I type anything.

The problem is, when I watch the NSLog as I type, it doesn't register a change of height until I have typed 4 characters on the new line. It is as if the sizeWithFont method is exactly four characters out. Here's a couple of screenshots showing what I mean: Height with three characters on line Height with four characters on line

Can anyone tell me what is going on?

like image 226
Ric Levy Avatar asked Feb 02 '26 19:02

Ric Levy


1 Answers

@Vladimir's comment is right I think - an NSString doesn't take into account the margins of a UITextField.

You could try getting the text preceding the cursor and creating a new UITextField that only contains that text.

Then if you call [tempTextField sizeToFit] on your new text field then it's bounds should be the size you are looking for.

like image 81
deanWombourne Avatar answered Feb 04 '26 10:02

deanWombourne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!