I am trying to change the height of a UITextView
based on the size of its content using textViewDidChange
delegate call. But text is pushed up a bit while the first line is entered and is corrected to old position when the next line is entered, This keeps on repeating for every alternate line added.
func textViewDidChange(textView: UITextView!) {
var computedHeightDifference = textView.contentSize.height - textView.frame.size.height
if(computedHeightDifference != 0){
textView.frame.size.height = textView.contentSize.height
}
}
I tried using textView.sizeToFit()
instead of the complete block but the text view blinks when each line is added(Same behaviour can be noticed in the notes field while adding new contact in the Phone application.
I have uploaded the complete code on GitHub
You're not setting the height large enough. You need to account for the text container's inset.
Do this:
func textViewDidChange(textView: UITextView!) {
var computedHeightDifference = textView.contentSize.height - (textView.frame.size.height + textView.textContainerInset.top + textView.textContainerInset.bottom)
if(computedHeightDifference != 0){
textView.frame.size.height = textView.contentSize.height + textView.textContainerInset.top + textView.textContainerInset.bottom
}
}