简体   繁体   English

根据行数动态更改文本视图的高度

[英]Dynamically change text view height based on number of lines

I am dynamically changing the height of my text view based on the number of lines in my text view. 我正在根据文本视图中的行数动态更改文本视图的高度。 I'd like the text view to start increasing in height after the 6th line. 我希望文本视图在第六行之后开始增加高度。 My current implementation is causing the text view to constantly increase in height because the line count is always greater than the previous count. 我当前的实现方式导致文本视图的高度不断增加,因为行数始终大于以前的行数。 I'd also like the text view to shrink as you remove lines: 我还希望在删除行时缩小文本视图:

func textViewDidChange(_ textView: UITextView) {

   let lineCount = numberOfLines(textView: textView)

      if lineCount > previousLineCount {
            previousLineCount = lineCount - 1
      }

      print("previous number of lines: \(previousLineCount) current number of lines: \(lineCount)" )

      if lineCount > 6 && lineCount > previousLineCount {
           self.layoutConstraint.constant += 4
      }
}

Any ideas? 有任何想法吗?

Given that you add leading , trailing , top and link the height constraint you can do 鉴于您添加了Leading,Trailing,top和link高度限制,您可以执行

func textViewDidChange(_ textView: UITextView) { 
   self.heightConstraint.constant = textView.contentSize.height
   self.view.layoutIfNeeded()
}

Why not: 为什么不:

textView.sizeToFit()

And don't forget to disable scrolling either in storyboard or: 并且不要忘记在故事板中禁用滚动或:

textView.scrollEnabled = false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM