How to change the TextView height dynamicly to a threshold and then allow scrolling?

后端 未结 7 1921
离开以前
离开以前 2020-12-16 04:39

I have a TextView that has a constraint of min height of 33. The scroll is disabled from the storyboard. The TextView should increase in height based on the content until it

相关标签:
7条回答
  • 2020-12-16 05:29

    It seems your code requires two changes, and it will work fine.

    1. Instead of min height of constraint provide max height of 100:

    1. Change code as below:

       import UIKit
      
      class ViewController: UIViewController, UITextViewDelegate
      {
          @IBOutlet weak var messageTextView: UITextView!
      
          let messageTextViewMaxHeight: CGFloat = 100
          override func viewDidLoad()
          {
              super.viewDidLoad()
              messageTextView.delegate = self
          }
      
          func textViewDidChange(textView: UITextView)
          {
              if textView.contentSize.height >= self.messageTextViewMaxHeight
              {
                  textView.scrollEnabled = true
              }
              else
                  {
                  textView.frame.size.height = textView.contentSize.height
                  textView.scrollEnabled = false // textView.isScrollEnabled = false for swift 4.0
              }
          }
      }
      
    0 讨论(0)
提交回复
热议问题