如何根据其内容调整 UITextView 的大小? [英] How do I size a UITextView to its content?

查看:42
本文介绍了如何根据其内容调整 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 的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆