【问题标题】:How to adjust the frame of UITextView as per its content如何根据内容调整 UITextView 的框架
【发布时间】:2012-08-08 15:01:18
【问题描述】:
在我的应用程序中,我需要在包含文本的文本视图中存储确切的区域(高度和宽度)。
我有一个宽度为 300 的 UITextView。现在假设用户写了一些文本,该文本仅填充了 150,即 TextView 宽度的 50%。我如何知道 textview 的多少部分包含文本? ?我只想存储 150 而不是 300 即我需要排除 textview 中不包含文本的冗余部分。
但是我已经能够通过使用 textview.contentSize.height 获得准确的高度。
但是 textview.contentSize.width 没有给出适当的结果
有什么建议吗???
【问题讨论】:
标签:
iphone
ios
ipad
xcode4.2
【解决方案1】:
你需要计算UITextView边界内的文本大小:
CGSize textSize = [@"Some text" sizeWithFont:[UIFont boldSystemFontOfSize:12] forWidth:CGRectGetWidth(textView) lineBreakMode:UILineBreakModeCharacterWrap];
从这里你可以使用 textSize.height 属性来设置你的 UITextView 的高度。
请记住,您可能需要调整字体大小和 forWidth: 大小以匹配您的 UITextView 的大小,但这应该可以帮助您入门。
【解决方案2】:
这直接来自我的工作代码:
//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);