IOS中键盘是在编辑控件获得第一响应者时出现,编辑控件有UITextField,UITextView等,这里以UITextField做为例子。
首先实现UITextFieldDelegate中的几个方法:
#pragma mark - UITextFieldDelegate -(BOOL)textFieldShouldBeginEditing:(UITextField*)textField { //注册键盘出现和消失的通知中心 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil]; // 键盘高度变化通知,ios5.0新增的 #ifdef __IPHONE_5_0 float version = [[[UIDevice currentDevice] systemVersion] floatValue]; if (version >= 5.0) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil]; } #endif return YES; } -(void)textFieldDidEndEditing:(UITextField*)textField { #ifdef __IPHONE_5_0 float version = [[[UIDevice currentDevice] systemVersion] floatValue]; if (version >= 5.0) { [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil]; } #endif [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil]; }
然后实现接收通知的方法:
- (void)keyboardWillShow:(NSNotification *)notification { NSDictionary *userInfo = [notification userInfo]; NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey]; CGRect keyboardRect = [aValue CGRectValue]; NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey]; NSTimeInterval animationDuration; [animationDurationValue getValue:&animationDuration]; [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:animationDuration]; //这里可以实现你想做的事情,比如聊天页面中聊天窗口的向上移动,以及编辑控件的移动等等。 [UIView setAnimationDidStopSelector:@selector(animationStopForEndEditing)]; [UIView setAnimationDelegate:self]; [UIView commitAnimations]; } - (void)keyboardWillHide:(NSNotification *)notification { NSDictionary* userInfo = [notification userInfo]; NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey]; NSTimeInterval animationDuration; [animationDurationValue getValue:&animationDuration]; [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:animationDuration]; //这里可以实现你想做的事情,比如聊天页面中聊天窗口的向上移动,以及编辑控件的移动等等。 [UIView commitAnimations]; }