Tag Archives: UITextView

How to resize a UITextView dynamically with Auto Layout

Resizing a UITextView (or a UIScrollView) dynamically on the fly isn’t easy – or so it seems at first. Should we move or squish the UIView? Should we create a new frame for the enclosing view and animate that? But no, those things worked fine in the days before Auto Layout. Nowadays we have the excellent UIStackView in which our text view may be embedded – so what are we to do?

Turns out the easiest way would be to change one of the constraints we have given our outermost stack view programmatically.

In my example I have a stack view that fills the screen, and inside it I have a text view for the user to read text, and a text field underneath it for text input. When the keyboard comes up, I’d like the text field to slide up and the text view to get smaller, and as soon as the user taps return I’d like everything to go back to where it was. Oh, and I’d like for this to work in portrait and landscape, and on all iPad sizes as well. Like in the animation above. Without going insane.

Here’s how we do that. Continue reading





How to keep a UITextView scrolled to the bottom

UITextViews are ideal for displaying large amounts of scrollable text on a small screen, or a portion of the screen. They’re also great for continuously adding text to them, which naturally appears at the bottom. However, doing so does not scroll the text upwards so that the user can see the latest addition by default.

To accomplish this, many sources suggest to add use the contentOffset property. While this works if another component (like a keyboard) may come into vision, it does not help to steady keep all the text in our text view at the bottom at all times. However, another method from the UITextView class can help us there: scrollRangeToVisible.

To use it, we need to define an NSRange struct and define the portion of the text content that we’d like to display. We don’t need to find out what the height of our text view is for this, it is indeed enough to simply specify the last line of our text content. The following code nippet will do that:

- (void)positionTextView {
    
    // scroll to the bottom of the content
    NSRange lastLine = NSMakeRange(self.textView.text.length - 1, 1);
    [self.textView scrollRangeToVisible:lastLine];
}

Call this whenever text is added to the text view, or changes to the text view arise from constraint changes, and your last line of text will always be scrolled to the bottom.