UITextview content moves up when textview is selected
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 h开发者_C百科ave 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.
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];
}
}
}
Check out three20:
Three20 is a collection of iPhone UI classes, like a photo viewer, and general utilities, like an HTTP disk cache. Three20 is derived from the Facebook iPhone app, which is one of the most downloaded iPhone apps ever.
Specifically, you'll want to take a look at TTTextEditor:
TTTextEditor is a UITextView which can grow in height automatically as you type. I use this for entering messages in Facebook Chat, and it behaves similarly to the editor in Apple's SMS app.
You'll find instructions on how to add three20 to your project here.
I made a subclass of UITextView just for that:
https://github.com/MatejBalantic/MBAutoGrowingTextView
It is an auto-layout based light-weight UITextView subclass which automatically grows and shrinks based on the size of user input and can be constrained by maximal and minimal height - all without a single line of code.
The class is made primarily for use in Interface builder and only works with Auto layout.
精彩评论