1. 程式人生 > >iOS鍵盤彈出與退回和文字框的完美適配

iOS鍵盤彈出與退回和文字框的完美適配

如上圖所示,需要編輯使用者的資訊,鍵盤需要根據所輸入的行來合理的顯示鍵盤位置

①,文字框新增監聽

//新增監聽

  [selfaddRegisterText:leftTitleRightText.textFieldRight];

//新增監聽

- (void)addRegisterText:(DoneTextField *)textField

{

    [[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(textFieldEdit:) name:UITextFieldTextDidBeginEditingNotification

object:textField];

}

②,鍵盤新增監聽

//監聽鍵盤,新增監聽

    [selfaddNotification];

- (void)addNotification

{

    [[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotificationobject:nil];

    [[NSNotificationCenterdefaultCenter] addObserver:selfselector

:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotificationobject:nil];

}

//鍵盤彈出

- (void)keyboardWillShow:(NSNotification *)notification

{

NSDictionary *keyInfo = [notification userInfo];

//獲取高度

id keyBoardValue = [keyInfo objectForKey:UIKeyboardFrameBeginUserInfoKey];

CGSize keyBoardSize = [keyBoardValue

CGRectValue].size;

//獲取鍵盤彈出時間

id keyBoardDurationValue = [keyInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];

//如果鍵盤蓋住文字框,則移動

CGFloat allH = CGRectGetMaxY(self.currentOperateTextRect)+keyBoardSize.height;

if (allH > (kScreenHeight-kNavH)) {

CGPoint backScrollViewPoint = self.backScrollView.contentOffset;

//相差的距離

        backScrollViewPoint.y =   allH - kScreenHeight;

//動畫效果

        [UIViewanimateWithDuration:[keyBoardDurationValue floatValueanimations:^{

self.backScrollView.contentOffset = backScrollViewPoint;

        } completion:^(BOOL finished) {

        }];

    }

}

//鍵盤隱藏

- (void)keyboardWillHide:(NSNotification *)notification

{

NSDictionary *keyInfo = [notification userInfo];

//獲取高度

id keyBoardValue = [keyInfo objectForKey:UIKeyboardFrameBeginUserInfoKey];

CGSize keyBoardSize = [keyBoardValue CGRectValue].size;

//獲取鍵盤彈出時間

id keyBoardDurationValue = [keyInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];

CGPoint backScrollViewPoint = self.backScrollView.contentOffset;

    backScrollViewPoint.y = -kNavH;

//動畫效果

    [UIViewanimateWithDuration:[keyBoardDurationValue floatValueanimations:^{

self.backScrollView.contentOffset = backScrollViewPoint;

    } completion:^(BOOL finished) {

    }];

}

注意:

@property (nonatomic,assign) CGRect currentOperateTextRect;

全域性變數,記錄啟用那個文字框的frame