I have an expanding "Message Toolbar" that works in a similar fashion as the Messages app message bar, where a user can type text and the whole bar should grow in height for each new line of text (until it hits a predefined max height). I have it setup using auto layout and the growing message bar works just fine. The problem though, is that for some reason each time I get to a new line of text in the message bar's UITextView, the top line gets slightly cutoff by moving to far up and out of the UITextView's frame.
Here is my code for when a user types into the message bar:
func messageToolbarDidUpdateText(messageToolbar: MessageToolbar, textView: UITextView)
{
// Expand message bar to fit text view
let newTextViewHeight = max(self.messageToolbarMinHeight - messageToolbar.textViewTopPadding - messageToolbar.textViewBottomPadding, min(self.messageToolbarMaxHeight - messageToolbar.textViewTopPadding - messageToolbar.textViewBottomPadding, textView.contentSize.height)) // Check that message bar doesn't exceed the limits
textView.frame.size = CGSizeMake(textView.frame.width, newTextViewHeight)
let newMessageBarHeight = max(self.messageToolbarMinHeight, min(self.messageToolbarMaxHeight, textView.contentSize.height + messageToolbar.textViewTopPadding + messageToolbar.textViewBottomPadding)) // Check that message bar doesn't exceed the limits
self.messageToolbar.heightConstraint.constant = newMessageBarHeight
self.view.updateConstraintsIfNeeded()
}
Here are screenshots of what I mean. Notice the gap in the first image at the top of the textview before the first line of text. This is expected to be there until the message bar reaches the max height and starts requiring new lines to be scrolled within the textview. But for some reason, even while the message bar is still not at it's max height, new lines cause the top line of text to be cutoff. Its not just a scroll offset either, as the textview doesn't allow scrolling until the message bar meets its max height:
Oh, sorry for necroposting, but I had the same problem and finally found a solution.
So basicly u neeed:
if textView.contentSize.height <= textView.height {
textView.scrollRangeToVisible(NSMakeRange(0, 0))
}
It will scroll text to correct position if u didn't reached maximum toolbar height. If u reached it, than ur text view content size is higher than its height and u shouldn't have this problem.
Edit: Credits to https://stackoverflow.com/a/19047464/1316040 for mentioning HPGrowingTextView. https://github.com/HansPinckaers/GrowingTextView for... well, existing https://github.com/KennethTsang/GrowingTextView for actual line of code scrollRangeToVisible