如何调整UITextView的同时在里面input?

我正在创build一个评论部分,很像Facebook在其iOS应用中使用它的消息部分。 我想要UITextView来调整高度,使我input的文本适合它,而不是你必须滚动才能看到溢出的文本。 任何想法如何我可以去做这个? 我看了可能使用CGRect分配给文本视图的大小和高度,然后匹配内容大小:

 CGRect textFrame = textView.frame; textFrame.size.height = textView.contentSize.height; textView.frame = textFrame; 

我假设我需要某种函数来检测文本何时到达UITextView的边界,然后调整视图的高度? 有没有人与这个相同的概念挣扎?

你可以在这个委托方法中调整框架,不要忘记将textView的委托设置为self。

 -(BOOL)textView:(UITextView *)_textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { [self adjustFrames]; return YES; } -(void) adjustFrames { CGRect textFrame = textView.frame; textFrame.size.height = textView.contentSize.height; textView.frame = textFrame; } 

这个解决scheme是针对iOS6和以前的…针对iOS7是指这个

StackOverflow答案

这是我的解决scheme,使用autolayouttextView.contentSize.height 。 在iOS8 Xcode6.3 beta4上testing。

最后有一个关于setContentOffset的问题。 当行数改变时,我把它放在避免“错误contentOffset”的假象。 它在最后一行下面增加了一个额外的不需要的空白,除非在更改约束后立即将其设置回来,否则它看起来不太好。 花了我几个小时弄清楚了这一点!

 // set this up somewhere let minTextViewHeight: CGFloat = 32 let maxTextViewHeight: CGFloat = 64 func textViewDidChange(textView: UITextView) { var height = ceil(textView.contentSize.height) // ceil to avoid decimal if (height < minTextViewHeight + 5) { // min cap, + 5 to avoid tiny height difference at min height height = minTextViewHeight } if (height > maxTextViewHeight) { // max cap height = maxTextViewHeight } if height != textViewHeight.constant { // set when height changed textViewHeight.constant = height // change the value of NSLayoutConstraint textView.setContentOffset(CGPointZero, animated: false) // scroll to top to avoid "wrong contentOffset" artefact when line count changes } } 

在保存UITextView的TableViewController上,更新来自tableViewDataSource的数据,放在单元格中,然后简单地调用它:

  tableView.beginUpdates() tableView.endUpdates() 

不像tableView.reloadData(),这不会调用resignFirstResponder

contentsize在ios 7中不起作用。试试这个:

 CGFloat textViewContentHeight = textView.contentSize.height; textViewContentHeight = ceilf([textView sizeThatFits:textView.frame.size].height + 9); 

首先为您的TextView设置最小高度限制:

 textView.heightAnchor.constraint(greaterThanOrEqualTo: view.heightAnchor, multiplier: 0.20) 

(确保你设置的是更大的或者更大的约束,这样如果内在的内容高度超过这个高度,就需要内在的内容高度)

或简单的常数

 textView.heightAnchor.constraint(greaterThanOrEqualToConstant: someConstant) 

在configuration你的textView时,将isScrollEnabled设置为false

 textView.isScrollEnabled = false 

现在当你在textView上input时,其内在的内容大小的高度会增加,并会自动将它推到下面的视图。