Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self sizing uitextview till specific height

I have an app which has chatting functionality where UITextview is used for entering the message. UITextview height has to be dynamic (if user enters the message, the height has to be changed according to the text length till a specific Height).

How can I achieve this?

like image 978
Midhun Narayan Avatar asked Jul 10 '26 23:07

Midhun Narayan


1 Answers

Disable Scrolling of textView.

enter image description here

enter image description here

TO Increase Height to a specific value and then enable scrolling.

Provide a maximum height constraint then add this code to your viewController

 class YourViewController: UIViewController, UITextViewDelegate
    {
        @IBOutlet weak var yourTextView: UITextView!

        let textViewMaxHeight: CGFloat = 100
        override func viewDidLoad()
        {
            super.viewDidLoad()
            yourTextView.delegate = self
        }

        func textViewDidChange(textView: UITextView)
        {
            if textView.contentSize.height >= self.textViewMaxHeight
            {
                textView.scrollEnabled = true
            }
            else
                {
                textView.frame.size.height = textView.contentSize.height
                textView.scrollEnabled = false
            }
        }
    }
like image 95
Anuraj Avatar answered Jul 14 '26 20:07

Anuraj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!