1

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This works fine except for pressing return, where it still gets hidden. It looks like one line breakage is not recognized. Do you know a way to fix this too?
Can you try putting some margins like self.textViewHeight.constant = textView.contentSize.height + 10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.