0

在我的应用程序中,我需要在包含文本的文本视图中存储确切的区域(高度和宽度)。

我有一个宽度为300的 UITextView 。现在假设用户写了一些文本,这些文本最多只能填充150 ,即TextView 宽度的50%。我怎么知道 textview 有多少部分包含文本?我只想存储150而不是300,即我需要排除 textview 中不包含文本的冗余部分。

但是,我已经能够通过使用textview.contentSize.height获得确切的高度。但是textview.contentSize.width没有给出适当的结果

有什么建议么????

4

2 回答 2

2

您需要计算 UITextView 范围内的文本大小:

CGSize textSize = [@"Some text" sizeWithFont:[UIFont boldSystemFontOfSize:12] forWidth:CGRectGetWidth(textView) lineBreakMode:UILineBreakModeCharacterWrap];

从这里你可以使用 textSize.height 属性来设置你的 UITextView 的高度。

请记住,您可能需要调整字体大小和forWidth:大小以匹配您的 UITextView 所具有的任何内容,但这应该可以帮助您入门。

于 2012-08-08T15:11:31.453 回答
0

这直接来自我的工作代码:

//Make the textView as big as needed for it to fit the message body
CGSize stringSize = [m.msg_body sizeWithFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:13]
                           constrainedToSize:CGSizeMake(self.view.frame.size.width, 9999) 
                               lineBreakMode:UILineBreakModeWordWrap];

messageTextView.frame = CGRectMake(0, 0, stringSize.width, stringSize.height + 10);
于 2012-08-08T15:53:54.543 回答