The text view being hidden by keyboard is a very common issue faced by iPhone/iPad developers. When you touch a text view, the text view becomes first responder and keyboard automatically appears. If the text view is lying somewhere in lower part of the screen, most probably it will get hidden under the keyboard. The solution is to scroll the text view up enough so that it comes above the keyboard. To do that, you need to add the text view in UIScrollView so that it can be scrolled up.
Here is the strategy:
Whenever keyboard appear, check if it is hiding the text view or not.
If it is hiding the text view, then scroll the text view up so that it becomes visible.
When the keyboard disappears, then scroll the text view to its original position.
Here is the sample code (similar code used in Lekh Diagram):
First register for the keyboard appearing/disappearing event:
- (void)keyboardWasShown:(NSNotification*)aNotification {
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
// get the keyboard height
double keyboardHeight = kbSize.height;
UIInterfaceOrientation currentOrientation = [[UIApplication sharedApplication] statusBarOrientation];
// The calculations are little different for landscape mode.
if (UIInterfaceOrientationLandscapeLeft == currentOrientation ||UIInterfaceOrientationLandscapeRight == currentOrientation ) {
keyboardHeight = kbSize.width;
}
// save the position of the scroll view, so that we can scroll it to its original position when keyboard disappears.
originalScrollOffset = scroller.contentOffset;
CGPoint cp = [editView convertPoint:editView.bounds.origin toView:[UIApplicationsharedApplication].keyWindow.rootViewController.view];
cp.y += editView.frame.size.height;
CGRect bounds = [[UIScreen mainScreen] applicationFrame];
double sh = bounds.size.height;
UIInterfaceOrientation currentOrientation = [[UIApplication sharedApplication] statusBarOrientation];
if (UIInterfaceOrientationLandscapeLeft == currentOrientation ||UIInterfaceOrientationLandscapeRight == currentOrientation ) {
sh = bounds.size.width;
}
// scroll if the keyboard is hiding the text view
if(cp.y > sh - keyboardHeight){
double sofset = cp.y - (sh - keyboardHeight);
CGPoint offset = scroller.contentOffset;
offset.y += sofset;
scroller.contentOffset = offset;
}
}
And when the keyboard disappears:
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
// restore the scroll position
scroller.contentOffset = originalScrollOffset;
}
The above code is used in "Lekh Diagram" ipad app. Lekh Diagrma is a sketch recognition diagramming app.