How do I size a UITextView to its content?(如何根据内容调整 UITextView 的大小?)
问题描述
有没有一种好方法可以调整 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 的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何根据内容调整 UITextView 的大小?


- 网上有没有好的 UIScrollView 教程? 2022-01-01
- GPS状态的广播接收器? 2022-01-01
- SetOnItemSelectedListener上的微调程序错误 2022-01-01
- Xcode 7.3 中带有 UILabel 的 UIStackView 2022-01-01
- 如何在 iPhone 模拟器中重置 NSUserDefaults 数据? 2022-01-01
- 在 Iphone SDK 的导航栏上添加多个按钮 2022-01-01
- 使用自动布局向 UIScrollView 添加动态大小的视图 2022-01-01
- UITextView 内容插图 2022-01-01
- URL编码Swift iOS 2022-01-01
- 类似于 Mail.app 的 iPad 模态视图控制器? 2022-01-01