目前负责的项目中 有很多页面都使用到textField,而且是多个TextFiled.当键盘出现时对视图的移动处理就成为了关键。
我的方法是,注册键盘frame发生变化的通知,然后在通知中将当前的textField的坐标转换为keyWindow中的坐标,同时获取键盘的坐标原点,计算出textField的maxFrame和键盘坐标原点之间的间距 从而让视图向上移动相应的距离。
有心人或许会注意到 每当textFiled发生变化时,通知中心都会发一个通知 因此我们只需要在通知的方法中,对视图的遮挡进行处理即可。
另一个要点就是:如何给键盘增加附属视图,我在项目中是对附属视图进行了封装,然后将附属视图添加在keyWindow上
```
//TODO:辅助视图
- (HHInputAccessoryView *)accessoryView{
if (_accessoryView == nil) {
_accessoryView = [[HHInputAccessoryView alloc]initWithTextFields:_textFields];
__weak typeof(&*self) weakSlef = self;
_accessoryView.delegate = weakSlef;
[HHKeyWindow addSubview:_accessoryView];
}
return _accessoryView;
}
```
//注册通知
```
[HHNotificationCenter addObserver:self selector:@selector(didReceiveKeyboardChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
```
//通知的处理
```
//TODO: 通知
- (void)didReceiveKeyboardChange:(NSNotification *)noti{
CGRect rect=[[noti.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
// UIKeyboardAnimationDurationUserInfoKey 对应键盘弹出的动画时间
CGFloat animationDuration = [[noti.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
NSInteger animationCurve = [[noti.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:animationDuration];
[UIView setAnimationCurve:(UIViewAnimationCurve)animationCurve];//设置添加按钮的动画类型
NSNumber *isShowKeyboardValue = [noti.userInfo objectForKey:UIKeyboardIsLocalUserInfoKey];
BOOL isShowKeyboard = isShowKeyboardValue.boolValue;
if (isShowKeyboard)
{
_keyboardRect = rect;
///键盘高度更改
[self.accessoryView setFrame:CGRectMake(0, rect.origin.y - 45 , HHMainScreenWidth, 45)];
self.currentTF = self.accessoryView.currentTF;
}else{
///键盘隐藏
[self.accessoryView setFrame:CGRectMake(0, HHMainScreenHeight, HHMainScreenWidth, 45)];
}
[UIView commitAnimations];
}
```
当当前的textFiled发生变化时
```
- (void)setCurrentTF:(UITextField *)currentTF{
_currentTF = currentTF;
[_currentTF becomeFirstResponder];
//对当前TF的最大坐标和键盘的坐标点进行比较,判断视图移动的距离
//坐标转化
_bgView.frame = CGRectMake(0, 0, HHMainScreenWidth, HHMainScreenHeight-50);
CGRect rectY = [currentTF convertRect:currentTF.frame toView:HHKeyWindow];
CGFloat currenMaxY = CGRectGetMaxY(rectY);
CGFloat keyboardY = _keyboardRect.origin.y-45;
if (_currentTF == _shopDescTF) {
currenMaxY += 20;
}
if (currenMaxY >= keyboardY) {
_bgView.frame = CGRectMake(0, -(currenMaxY-keyboardY)-10, HHGet_W(_bgView), HHGet_H(_bgView));
}
}
```