是否有一个好的方法来调整UITextView的大小以符合其内容?例如,我有一个包含一行文本的UITextView:

"Hello world"

然后我添加了另一行文本:

"Goodbye world"

在Cocoa Touch中是否有一个好的方法来获取矩形来保存文本视图中的所有行,这样我就可以相应地调整父视图?

另一个例子是,查看Calendar应用程序中用于事件的notes字段——注意单元格(以及它包含的UITextView)如何展开以保存notes字符串中的所有文本行。


当前回答

下面是答案,如果你需要在staticTableView中动态调整textView和tableViewCell的大小

[https://stackoverflow.com/a/43137182/5360675][1]

其他回答

对于iOS 7.0,不是将frame.size.height设置为contentSize. height。使用[textView sizeToFit]。

看这个问题。

我找到了一种方法,根据里面的文本调整文本字段的高度,并根据文本字段的高度在下面安排一个标签!这是代码。

UITextView *_textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, 300, 10)];
NSString *str = @"This is a test text view to check the auto increment of height of a text view. This is only a test. The real data is something different.";
_textView.text = str;

[self.view addSubview:_textView];
CGRect frame = _textView.frame;
frame.size.height = _textView.contentSize.height;
_textView.frame = frame;

UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(10, 5 + frame.origin.y + frame.size.height, 300, 20)];
lbl.text = @"Hello!";
[self.view addSubview:lbl];

你试过[textView sizeThatFits:textView. txt]吗?范围)?

编辑:sizeThatFits返回大小,但并不实际调整组件的大小。我不确定如果这是你想要的,或者如果[textView sizeToFit]是更多的你要寻找的。无论哪种情况,我不知道它是否完全适合你想要的内容,但这是第一件要尝试的事情。

根据我有限的经验,

- (CGSize)sizeWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode

不尊重换行符,所以你最终可以得到比实际需要的更短的CGSize。

- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size

看起来很尊重换行符。

同样,文本也不是在UITextView顶部渲染的。在我的代码中,我将UITextView的新高度设置为比sizeOfFont方法返回的高度大24个像素。

希望这能有所帮助:

- (void)textViewDidChange:(UITextView *)textView {
  CGSize textSize = textview.contentSize;
  if (textSize != textView.frame.size)
      textView.frame.size = textSize;
}