这是一个非常常见的话题,并且有很多答案。
情况:我有一个全屏(减去工具栏)UITextView,底部有一个 UIToolbar。当 UITextView 获得第一响应者时,我想让工具栏与键盘一起向上滑动并添加一个“完成”按钮,该按钮将关闭键盘。
到目前为止:基于这个例子,我已经完全工作了。除了当我放入工具栏时工具栏没有动画的[textView becomeFirstResponder];
事实viewDidLoad
。即使keyboardWillShow
被称为。有人有什么主意吗?
代码:这样您就不必查看示例代码,这就是正在发生的事情:
在 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];
}
在键盘将显示:
- (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];
}