问题
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:


Can anyone tell me what is going on?
回答1:
@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.
来源:https://stackoverflow.com/questions/5990650/why-does-nsstring-sizewithfont-return-the-wrong-size