(自用)鍵盤遮擋輸入框問題

看了其他人的博客,根據(jù)需求寫的:

要實現(xiàn)的效果就是,如果鍵盤遮住的輸入框,那么要把view上移,所以需要拿到當(dāng)前輸入框的位置,控制器實現(xiàn)UITextFiled的代理,有一個代理方法

//開始編輯
- (void)textFieldDidBeginEditing:(UITextField*)textField
{
    self.tempTextField = textField;
}

當(dāng)點擊輸入框的時候,拿到這個輸入框,變成全局變量,在通知的觸發(fā)事件里面,進行比較,如果遮住了,就需要view上移一段距離(根據(jù)需求調(diào)節(jié)),當(dāng)鍵盤需要消失的時候,還需要把view整體降下來

1.首先注冊兩個通知,監(jiān)聽鍵盤出現(xiàn)和消失

//注冊通知
 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

2.接著實現(xiàn)通知觸發(fā)事件

  • 我在這里還定義了一個view的偏移量offsetY,方便鍵盤回收的時候,調(diào)節(jié)view的frame.
  • 有一個問題就是如果輸入完之后,鍵盤沒回收,又點擊了另外一個輸入框,會出現(xiàn)問題,所以我需要做一個判斷,上一個鍵盤到底有沒有回收,如果沒有,我會先回收鍵盤,然后根據(jù)第二個鍵盤調(diào)節(jié)view
#pragma mark--通知事件
- (void)keyboardWillShow:(NSNotification*)noti
{
    //根據(jù)當(dāng)前輸入框調(diào)整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;

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容