在点击录入框时键盘会自动升起,这是系统自动操作,但很多时候键盘会把视图中控件挡住,这样我们就得对键盘升做一些操作,
首先,要监听键盘升起事件,系统在升起键盘时会发出UIKeyboardWillShowNotification信号,要捕捉它并设置处理函数。
[[NSNotificationCenterdefaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
keyboardWillShow是处理函数,在函数做视图位置上升变化。键盘处理函数中改变视图位置要注意个问题,如果键盘弹出不是英文键盘,会收到多次信号,这是因为系统在切换键盘时都会发出keyboardWillShow信号。比如现在使用的是中文输入法,系统首先弹出键盘是英文键盘会发出信号,然后在切换到中文键盘又会发出信号,
还要监听键盘降下事件,在键盘落下时把视图位置反回原处,键盘落下系统发出UIKeyboardWillHideNotification信号
[[NSNotificationCenterdefaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
键盘处理函数
-(void) keyboardWillShow:(NSNotification *)note{
// 取得键盘位置高度
CGRect keyboardBounds;
[[note.userInfovalueForKey:UIKeyboardFrameEndUserInfoKey]getValue: &keyboardBounds];
NSNumber *duration = [note.userInfoobjectForKey:UIKeyboardAnimationDurationUserInfoKey];
NSNumber *curve = [note.userInfoobjectForKey:UIKeyboardAnimationCurveUserInfoKey];
// Need to translate the bounds to account for rotation.
keyboardBounds = [self.viewconvertRect:keyboardBounds toView:nil];
//改变视图位置
CGRect containerFrame = containerView.frame;
containerFrame.origin.y =self.view.bounds.size.height - keyboardBounds.size.height;
// animations settings
[UIViewbeginAnimations:nilcontext:NULL];
[UIViewsetAnimationBeginsFromCurrentState:YES];
[UIViewsetAnimationDuration:[duration doubleValue]];
[UIViewsetAnimationCurve:[curve intValue]];
// set views with new info
containerView.frame = containerFrame;
// commit animations
[UIViewcommitAnimations];
}
-(void) keyboardWillHide:(NSNotification *)note{
NSNumber *duration = [note.userInfoobjectForKey:UIKeyboardAnimationDurationUserInfoKey];
NSNumber *curve = [note.userInfoobjectForKey:UIKeyboardAnimationCurveUserInfoKey];
// get a rect for the textView frame
CGRect containerFrame = containerView.frame;
containerFrame.origin.y =self.view.bounds.size.height - containerFrame.size.height + 20;
// animations settings
[UIViewbeginAnimations:nilcontext:NULL];
[UIViewsetAnimationBeginsFromCurrentState:YES];
[UIViewsetAnimationDuration:[duration doubleValue]];
[UIViewsetAnimationCurve:[curve intValue]];
// set views with new info
containerView.frame = containerFrame;
// commit animations
[UIViewcommitAnimations];
}
也可以监听某些按件,让某个控件关闭键盘
-(IBAction)sendMessage_Click:(id)sender
{
[textViewresignFirstResponder];
}