如何在 UITextView 中键入时调整其大小



我正在创建一个评论部分,就像Facebook在其iOS应用程序中用于消息传递部分一样。我希望UITextView调整高度大小,以便我键入的文本适合其中,而不必滚动才能看到溢出的文本。任何想法我可以怎么做?我已经研究过可能使用分配给文本视图大小和高度的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;
}

此解决方案适用于 iOS6 及更早版本...对于 iOS7,请参阅此

堆栈溢出答案

这是我

的解决方案,使用自动布局textView.contentSize.height。在iOS8 Xcode6.3 beta4上测试。

最后有一个关于setContentOffset的问题。我把它放在避免行数更改时"错误的内容偏移"伪影。它在最后一行下方添加了额外的不需要的空格,除非您在更改约束后立即将其设置回来,否则看起来不是很好。花了我几个小时才弄清楚这一点!

// 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
    }
}

首先为 TextView 设置最小高度约束:

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

(确保设置的约束大于或等于约束,以便如果内部内容高度大于此高度,则采用内部内容高度)

或简单常数

textView.heightAnchor.constraint(greaterThanOrEqualToConstant: someConstant)

配置文本视图时,将"滚动启用"设置为 false

textView.isScrollEnabled = false

现在,当您在 textView 上键入时,其固有内容大小高度将增加,并且会自动将视图推到其下方。

在保存 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);

最新更新