Why does NSString sizeWithFont: return the wrong size?

I need to work out the height of the UITextView from top to bottom to the cursor. I crop the text that it contains (so it only fits the cursor) and then using the NSString method sizeWithFont:constrainedToSize:lineBreakMode:to generate the height, for example:

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

He does this every time I print something.

The problem is that when I look at NSLog as I type, it does not register a change in height until I type 4 characters on a new line. It is as if the method sizeWithFontwere exactly four characters long . Here are some screenshots showing what I mean: Height with three characters on lineHeight with four characters on line

Can someone tell me what is going on?

+3
source share
1 answer

@ Vladimir , - NSString UITextField.

UITextField, .

, [tempTextField sizeToFit] , , .

+6

All Articles