Although this problem has been described on many occasions, I'm asking this in reference and in the context of IOS7 & Apple's proposed solution which is described in the docs here:
Problem: Keyboard covers a text view. Solution: Using Apples suggested method, attach observers to keyboard events, scroll a UIScrollView uo by the keyboard height.
I've created a simple implementation of a single texfield which is a subview of a scrollview in a view controller, ensured the view controller is delegates of both and that that the correct methods are getting called.
TestViewController.h
#import <UIKit/UIKit.h>
@interface TestViewController : UIViewController <UITextFieldDelegate, UIScrollViewDelegate>
@end
TestViewController.m
#import "TestViewController.h"
@interface TestViewController ()
@property (weak, nonatomic) IBOutlet UITextField *testTextField;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@end
@implementation TestViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self registerForKeyboardNotifications];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)registerForKeyboardNotifications
{
NSLog(@"registerForKeyboardNotifications got called");
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
}
// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSLog(@"keyboardWasShown got called");
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
// If active text field is hidden by keyboard, scroll it so it's visible
// Your app might not need or want this behavior.
CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;
if (!CGRectContainsPoint(aRect, self.testTextField.frame.origin) ) {
[self.scrollView scrollRectToVisible:self.testTextField.frame animated:YES];
}
}
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
NSLog(@"keyboardWillBeHidden got called");
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
}
- (BOOL) textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return TRUE;
}
@end