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

后端 未结 7 1919
离开以前
离开以前 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:08

    For an easy way to solve your problem is to change the frame of the textView whenever textViewDidChange invokes. UITextView actually is a UIScrollView. If you have to use constraint, you have to change the constant of the constraint. Here is my code:

    import UIKit
    
    let width = UIScreen.mainScreen().bounds.width
    
    class ViewController: UIViewController, UITextViewDelegate {
    
        var messageTextView: UITextView!
        let messageTextViewMaxHeight: CGFloat = 100
    
        override func viewDidLoad() {
            super.viewDidLoad()
            view.backgroundColor = UIColor.redColor()
            messageTextView = UITextView(frame: CGRectMake(0, 200 - 33, width, 33))
            messageTextView.backgroundColor = UIColor.whiteColor()
            view.addSubview(messageTextView)
            self.messageTextView.delegate = self
        }
    
        //
        let bottomY: CGFloat = 200
    
        func textViewDidChange(textView: UITextView) {
            let formerRect = textView.frame
    
            if formerRect.height > messageTextViewMaxHeight{
    
            }
            else{
                textView.frame = CGRectMake(formerRect.origin.x, bottomY - textView.contentSize.height, width, textView.contentSize.height)
            }
        }
    } 
    

提交回复
热议问题