我试图通过修剪光标后的所有文本来计算出文本视图到光标的大小,然后使用 NSString 的 sizeWithFont 方法,如下所示:
NSString *string = [myTextView.text substringToIndex:myTextView.selectedRange.location];
CGSize size = [string sizeWithFont:myTextView.font constrainedToSize:myTextView.frame.size lineBreakMode:UILineBreakModeWordWrap];
不幸的是,这永远不会返回完全正确的大小,可能是因为文本有边距,所以它的实际宽度小于 UITextView 的宽度(感谢这个问题来解决这个问题)。
因此,我需要计算出边距的大小,然后从 UITextView 的大小中减去边距的大小,以获得文本区域的实际大小。有谁知道该怎么做?
I am trying to work out the size of a size of a textView up to the cursor by trimming all the text after the cursor, and then using NSString's sizeWithFont
method, like so:
NSString *string = [myTextView.text substringToIndex:myTextView.selectedRange.location];
CGSize size = [string sizeWithFont:myTextView.font constrainedToSize:myTextView.frame.size lineBreakMode:UILineBreakModeWordWrap];
Unfortunately, this never returns quite the right size, probably because the text has margins, so its actual width is less than UITextView's width (thanks to the answerers of this question for working that out).
So I need to work out the size of the margins, and subtract that from the UITextView's size to get the actual size of the text area. Does anyone know how to do that?
发布评论
评论(2)
我建议
I'd suggest
不幸的是,答案似乎是 UITextView 中没有边距 - 您只需通过在其后面放置一个视图来模拟边距,并使 UITextView 更窄。如果需要背景随文本滚动,可以监听
scrollViewDidScroll:
。Unfortunately it looks like the answer is that there is no margin in UITextView - you just have to simulate one by putting a view behind it, and making the UITextView narrower. If you need the background to scroll with the text, you can listen for
scrollViewDidScroll:
.