IOS解决虚拟键盘遮盖textfield问题

(一)定义键盘即将弹出通知和键盘即将隐藏通知;

- (void)setupNotification{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldBeginEditing:) name:UITextFieldTextDidBeginEditingNotification object:nil];
}

(二)计算出键盘的高度;

//动态计算键盘的高度避免textfield被键盘遮盖;
- (void)keyboardWillShow:(NSNotification *)notification
{
    NSDictionary *userInfo = [notification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    CGFloat offset = (CGRectGetMaxY(self.editTextField.frame)+150.0f)-(CGRectGetHeight(self.view.frame)-CGRectGetHeight(keyboardRect));
    
    double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    if (offset > 0) {
        [UIView animateWithDuration:duration animations:^{
            self.view.frame = CGRectMake(0.0f, -offset, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame));
        }];
    }
}


(三)获取当前编辑的textfield;

//获取当前正在编辑的textfield
- (void)textFieldBeginEditing:(NSNotification *)notification
{
    self.editTextField = [notification object];
}


(四)恢复原状;

//恢复原状
- (void)keyboardWillHide:(NSNotification *)notification
{
    double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        self.view.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame));
    }];
}


你可能感兴趣的:(IOS解决虚拟键盘遮盖textfield问题)