iOS Swift3 TextView line at wrong position

I have a textView which i use as an input field for chatMessages. I want it to expand if there is more text than could fit in one row.

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

I set a height constraint programmatically if the user enters something inside the textView.

enter image description here <- For one liners it looks fine.

enter image description here <- After you press enter it gets hidden.

enter image description here <- The second enter shows it up again.

What am i doing wrong here? I try to recreate the look of whatsapp / imessage, where this hiding does not happen.

Upvotes: 1

Views: 342

Answers (1)

The Mach System
The Mach System

Reputation: 6963

This is because you are changing the size in the wrong delegate function. The delegate textViewDidChange is called after you finished editing (resignFirstResponder gets called).

You should put your code to change the height in this function instead:

optional func textView(_ textView: UITextView, 
    shouldChangeTextIn range: NSRange, 
       replacementText text: String) -> Bool

So this will change the height of the UITextView as you type not after you finished typing.

Upvotes: 2

Related Questions