R – UITextview content moves up when textview is selected

iphonescrolluitextview

I am pretty new to this iPhone dev thing but so far I have built a pretty good app but I have stumbled into this problem that for the life of me I cannot seem to solve.

Basically the app is a chat application for social site. Everything is working 100% except the input box which currently is a UITextbox. This works fine however I would like the box to grow and be a multiline UITextbox with scroll. I replaced the UITextbox with a UITextview and all is good. I have the UITextview expanding as the user enters text however I have one slight problem that is driving me nuts.

When the UITextview gets focus it shifts the cursor and any text in there up just out of view. The UITextview I have set to display 2 lines by default and then as the height of the text goes beyond those two lines I would like the box to grown (which it does) and the text to remain scrolled up so you can see what you are typing. If you look at the SMS app on the iPhone this is exactly how I would like it work.

Any words of wisdom would be greatly appreciated.

Best Answer

I think Blaenk answered perfectly (that was going to be my answer). But just in case you don't want to include Three20 in your project (it's kinda big), below is the relevant code from TTTextEditor. You should be able to call this from wherever you are expanding the text view.

- (void)scrollContainerToCursor:(UIScrollView*)scrollView {
  if (_textView.hasText) {
    if (scrollView.contentSize.height > scrollView.height) {
      NSRange range = _textView.selectedRange;
      if (range.location == _textView.text.length) {
        [scrollView scrollRectToVisible:CGRectMake(0,scrollView.contentSize.height-1,1,1)
          animated:NO];
      }
    } else {
      [scrollView scrollRectToVisible:CGRectMake(0,0,1,1) animated:NO];
    }
  }
}