Why does NSString sizeWithFont: return the wrong size?

喜你入骨 提交于 2020-01-01 06:52:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!