4

In iOS how do you make a UITextView scrollable and responsive to touch when there's little or no content?

In my app, once text fills up the textview, scrollbars appears and I can scroll around. Less than that though, and since all the content is withen the frame of the UITextView, it's static and doesn't move.

What I want would work like the iPhone Notes application, whether there's one line of text or even when a note is empty, you can scroll the view.

Right now I'm only using a UITextView, and I'm having a hard time understanding whether a UIScrollView is also needed.

I wasn't able to find a question specific to this issue. Thanks!

Malcolm Bastien
  • 115
  • 1
  • 6

3 Answers3

14

For anyone that stumbles upon this page in the future:

I was able to achieve this by simply enabling alwaysBounceVertical, and making sure User interaction and scrolling was enabled.

self.textView.scrollEnabled = YES;
self.textView.userInteractionEnabled = YES;
self.textView.alwaysBounceVertical = YES;

For Swift 3.0:

    textView.alwaysBounceVertical = true
    textView.isUserInteractionEnabled = true
    textView.isScrollEnabled = true
serenn
  • 1,828
  • 1
  • 15
  • 11
  • After all the searching I have done, This is the first answer I remember seeing that mentions the "alwaysBounceVertical". Solved my same issue right away. Thank You for that. – ChrisOSX Mar 14 '17 at 08:18
1

Try this, it should be the only line you need:

textView.alwaysBounceVertical = true

Thanks to Serenn's answer.

Linus
  • 423
  • 5
  • 12
0

Yep, you'll need to start with a UIScrollView. Then add the text view and set it's autosizing properties to stretch and fill the view (click each of the two inner arrows that cross each other)

Now when your text is updated, you'll need to reset the size of your main view based on the content size of the textView.

CGRect frame = textView.frame;
frame.size.height = textView.contentSize.height;
self.view.frame = frame;

For this to work when the text gets to the bottom of the screen, it will need to be called in the textViewDidChange: method of the UITextView delegate. Once you get it working, I'd recommend adding in some logic to keep it from firing after every key press. Maybe make sure the contentSize.height has actually increased before you reset the view frame.

bgolson
  • 3,460
  • 5
  • 24
  • 41