This is a pretty common topic and has many answers out there.
Situation: I have a full screen (minus toolbar) UITextView with a UIToolbar at the bottom. when the UITextView gets first responder I want to have the toolbar slide up with the keyboard and add a "done" button which will dismiss the keyboard.
So far: I have this completely working, based on this example. Except for the fact that when I put [textView becomeFirstResponder];
in my viewDidLoad
then the toolbar doesn't animate. Even though keyboardWillShow
is called. Does anyone have any idea?
Code: Just so you don't have to check out the example code this is what is happening:
In viewDidLoad:
- (void)viewDidLoad {
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[nc addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
[textView becomeFirstResponder];
[super viewDidLoad];
}
In keyboardWillShow:
- (void)keyboardWillShow:(NSNotification *)notification {
NSLog(@"keyboard will show");
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationCurve:[[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue]];
[UIView setAnimationDuration:[[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self
action:@selector(keyboardDone)];
NSMutableArray *toolbarItems = [NSMutableArray arrayWithArray:[toolbar items]];
[toolbarItems addObject:doneButton];
[toolbar setItems:toolbarItems];
CGRect frame = self.view.frame;
frame.size.height -= [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] CGRectValue].size.height;
self.view.frame = frame;
[UIView commitAnimations];
}