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

"Hello world"

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

"Goodbye world"

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

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


当前回答

如果你手边没有UITextView(例如,你正在调整表格视图单元格的大小),你将不得不通过测量字符串来计算大小,然后在UITextView的每一侧占用8 pt的填充。例如,如果你知道你的文本视图的期望宽度,并想要计算出相应的高度:

NSString * string = ...;
CGFloat textViewWidth = ...;
UIFont * font = ...;

CGSize size = CGSizeMake(textViewWidth - 8 - 8, 100000);
size.height = [string sizeWithFont:font constrainedToSize:size].height + 8 + 8;

在这里,每个8都是四个填充边中的一个,100000只是一个非常大的最大尺寸。

实际上,您可能想要添加额外的字体。通向高处;这将在文本下方添加一个空行,如果文本视图正下方有视觉上沉重的控件,这可能会看起来更好。

其他回答

禁用滚动

添加constaints

然后添加文本

[yourTextView setText:@"your text"];
[yourTextView layoutIfNeeded];

如果你使用UIScrollView,你也应该添加这个;

[yourScrollView layoutIfNeeded];

-(void)viewDidAppear:(BOOL)animated{
    CGRect contentRect = CGRectZero;

    for (UIView *view in self.yourScrollView.subviews) {
         contentRect = CGRectUnion(contentRect, view.frame);
    }
    self.yourScrollView.contentSize = contentRect.size;
}

我回顾了所有的答案,所有都保持固定的宽度和调整只有高度。如果你想调整宽度,你可以很容易地使用这个方法:

当配置文本视图时,将滚动设置为禁用

textView.isScrollEnabled = false

然后在委托方法func textViewDidChange(_ textView: UITextView)添加以下代码:

func textViewDidChange(_ textView: UITextView) {
    let newSize = textView.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))
    textView.frame = CGRect(origin: textView.frame.origin, size: newSize)
}

输出:

希望这能有所帮助:

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

更新

你需要做的关键事情是关闭UITextView中的滚动。

myTextView.scrollEnabled = @NO

原来的答案

要在UITableViewCell中创建一个动态大小的UITextView,我发现以下组合在Xcode 6和iOS 8 SDK中有效:

Add a UITextView to a UITableViewCell and constrain it to the sides Set the UITextView's scrollEnabled property to NO. With scrolling enabled, the frame of the UITextView is independent of its content size, but with scrolling disabled, there is a relationship between the two. If your table is using the original default row height of 44 then it will automatically calculate row heights, but if you changed the default row height to something else, you may need to manually switch on auto-calculation of row heights in viewDidLoad: tableView.estimatedRowHeight = 150; tableView.rowHeight = UITableViewAutomaticDimension;

对于只读动态大小的uitextview,就是这样。如果你允许用户在你的UITextView中编辑文本,你还需要:

实现UITextViewDelegate协议的textViewDidChange:方法,并告诉tableView在每次文本被编辑时重新绘制自己: - (void)textViewDidChange:(UITextView *)textView; { [tableView beginUpdates]; [tableView endUpdates]; } 别忘了在某个地方设置UITextView委托,在Storyboard或者tableView:cellForRowAtIndexPath:

迅速:

textView.sizeToFit()