问题描述
有没有一种好方法可以调整 UITextView 的大小以符合其内容?比如说我有一个 UITextView 包含一行文本:
Is there a good way to adjust the size of a UITextView to conform to its content? Say for instance I have a UITextView that contains one line of text:
"Hello world"
然后我添加另一行文本:
I then add another line of text:
"Goodbye world"
在 Cocoa Touch 中是否有一个好方法可以获取 rect 来保存文本视图中的所有行,以便我可以相应地调整父视图?
Is there a good way in Cocoa Touch to get the rect that will hold all of the lines in the text view so that I can adjust the parent view accordingly?
作为另一个示例,查看日历应用程序中事件的注释字段 - 请注意单元格(以及它包含的 UITextView)如何扩展以容纳注释字符串中的所有文本行.
As another example, look at the notes' field for events in the Calendar application - note how the cell (and the UITextView it contains) expands to hold all lines of text in the notes' string.
推荐答案
这适用于 iOS 6.1 和 iOS 7:
This works for both iOS 6.1 and iOS 7:
- (void)textViewDidChange:(UITextView *)textView
{
CGFloat fixedWidth = textView.frame.size.width;
CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
CGRect newFrame = textView.frame;
newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
textView.frame = newFrame;
}
或在 Swift 中(适用于 iOS 11 中的 Swift 4.1)
Or in Swift (Works with Swift 4.1 in iOS 11)
let fixedWidth = textView.frame.size.width
let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
textView.frame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
如果您想要支持 iOS 6.1,那么您还应该:
If you want support for iOS 6.1 then you should also:
textview.scrollEnabled = NO;
这篇关于如何根据内容调整 UITextView 的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)