使用 sizeWithFont:constrainedToSize:lineBreakMode 计算 UITextView 文本的高度似乎不会返回正确的结果

人气:937 发布:2022-10-16 标签: cocoa-touch uikit uitextview

问题描述

我正在尝试计算受 UITextView 约束的文本的高度,但它似乎没有返回正确的结果.

I'm trying to calculate the height of the text constrained by a UITextView but it doesn't seem to return correct results.

这是我的代码:

- (void)textViewDidChange:(UITextView *)aTextView {
    CGSize textSize = [aTextView.text sizeWithFont:aTextView.font constrainedToSize:aTextView.frame.size lineBreakMode:UILineBreakModeWordWrap];
    counter.text = [NSString stringWithFormat:@"%f", textSize.height];
}

您可以下载 示例项目和一个简短的截屏视频说明问题 (418 KB).

总而言之,问题是当我在行尾键入一个长单词时,该单词会移动到下一行,但是发生这种情况时字符串的高度没有正确调整.

In summary, the problem is that when I type a long word at the end of a line, the word is moved to the next line, but the height of the string isn't correctly adjusted when it happens.

任何帮助表示赞赏.

最好的,托马斯.

Best, Thomas.

附:: 它发生在 iPhone SDK 3.1.3

P.S. : It happens with the iPhone SDK 3.1.3

推荐答案

问题是 UITextField 在它实际绘制和环绕文本的区域周围有一点边距.据我所知,没有程序化的方式来获得这个大小,但只需从大小中减去 6 左右就可以使其行为正常.

The issue is that the UITextField has a slight margin around the area it actually draws and wraps the text. As far as I know there is no programatic way to get this size, but just subtracting 6 or so from the size should make it behave appropriately.

1,006