目前負責的項目中 有很多頁面都使用到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));
}
}
```