Tutorial :Scrolling UITextView programmatically



Question:

I'm implementing some simple text chatting capabilities in my app and I'm having issues with scrolling the UITextView programmatically. I'm using a UITextView created in Interface Builder that appends a new line and some text to the preexisting text. When the new text is added it should scroll to the bottom.

I built a test application to nail down the concept before adding it to my app. The text in the UITextView updates with the text from a UITextField, however no scrolling occurs.

- (IBAction)enteredText {    CGPoint currentPosition = [textWindow contentOffset];  [textWindow setText:[NSString stringWithFormat:@"%@\n%@", textWindow.text, textInput.text]];  [textWindow setContentOffset:currentPosition animated:NO];  [textWindow scrollRangeToVisible:NSMakeRange([textWindow.text length], 0)];  [textInput setText:@""];  [textInput becomeFirstResponder];  

}

I remember implementing a very similar feature in another application I developed a while ago andfrom what I remember the code is similar. The only difference is that the earlier application was for iPhone OS 2 but this one is for 3.0. I read in some forums that the 3.0 beta had some issues with scrolling when the UITextView was created in Interface Builder. I checked the current release notes and I didn't see anything indicating that.

Edit: The IB action is called because text is updated in the UITextView. And "Cancellable Content Touches" is checked.

Edit: Confirmed that the same code works on 2.2.1 but not 3.0


Solution:1

I found that after the user has tapped on the UITextView the scrolling begins to work. So after I loaded this particular view I temporarily set the UITextView as FirstResponder, then the UITextField as FirstResponder:

[myChatRoomViewController.chatWindow becomeFirstResponder];  [myChatRoomViewController.input becomeFirstResponder];  

The scrolling then happened automatically, albeit it seemed less smoother than what I remembered in iPhone OS 2.


Solution:2

Are you sure the IBAction is getting called? If so, try making sure that “Cancellable Content Touches” is checked in Interface Builder. This should solve the problem you hinted about in your post.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »