看了其他人的博客,根據需求寫的:
要實現的效果就是,如果鍵盤遮住的輸入框,那么要把view上移,所以需要拿到當前輸入框的位置,控制器實現UITextFiled的代理,有一個代理方法
//開始編輯
- (void)textFieldDidBeginEditing:(UITextField*)textField
{
self.tempTextField = textField;
}
當點擊輸入框的時候,拿到這個輸入框,變成全局變量,在通知的觸發事件里面,進行比較,如果遮住了,就需要view上移一段距離(根據需求調節),當鍵盤需要消失的時候,還需要把view整體降下來
1.首先注冊兩個通知,監聽鍵盤出現和消失
//注冊通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
2.接著實現通知觸發事件
- 我在這里還定義了一個view的偏移量offsetY,方便鍵盤回收的時候,調節view的frame.
- 有一個問題就是如果輸入完之后,鍵盤沒回收,又點擊了另外一個輸入框,會出現問題,所以我需要做一個判斷,上一個鍵盤到底有沒有回收,如果沒有,我會先回收鍵盤,然后根據第二個鍵盤調節view
#pragma mark--通知事件
- (void)keyboardWillShow:(NSNotification*)noti
{
//根據當前輸入框調整view
CGFloat textFieldY = kScreenHigh - self.tempTextField.frame.origin.y;
CGFloat textFieldHeight = self.tempTextField.frame.size.height;
NSDictionary* info = [noti userInfo];
CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
//鍵盤高度
CGFloat keyboardHeight = keyboardSize.height;
// NSLog(@"輸入框高度%f鍵盤高度%f",textFieldY - textFieldHeight,keyboardHeight);
//在第二個鍵盤出來前,判斷上個鍵盤的偏移量 ,退回去
if (self.offsetY > 0) {
[UIView animateWithDuration:0.5f delay:0.f usingSpringWithDamping:10.f initialSpringVelocity:1.f options:UIViewAnimationOptionCurveEaseInOut animations:^{
CGRect oldframe = self.view.frame;
oldframe.origin.y += self.offsetY;
self.view.frame = oldframe;
} completion:nil];
self.offsetY = 0;
}
//判斷鍵盤是否擋住輸入框
if (keyboardHeight >= textFieldY) {
// NSLog(@"輸入框高度%f鍵盤高度%f",textFieldY - textFieldHeight,keyboardHeight);
//偏移量 保存下來
self.offsetY = keyboardHeight - textFieldY + textFieldHeight;
[UIView animateWithDuration:0.5f delay:0.f usingSpringWithDamping:10.f initialSpringVelocity:1.f options:UIViewAnimationOptionCurveEaseInOut animations:^{
CGRect oldframe = self.view.frame;
oldframe.origin.y -= self.offsetY;
self.view.frame = oldframe;
} completion:nil];
}else{
self.offsetY = 0;
}
}
- 還有鍵盤消失的
- (void)keyboardWillHide:(NSNotification*)noti
{
[UIView animateWithDuration:0.5f delay:0.f usingSpringWithDamping:10.f initialSpringVelocity:1.f options:UIViewAnimationOptionCurveEaseInOut animations:^{
CGRect oldframe = self.view.frame;
oldframe.origin.y += self.offsetY;
self.view.frame = oldframe;
} completion:nil];
self.offsetY = 0;
}