(自用)键盘遮挡输入框问题

2016-08-19  本文已影响50人  马路的尽头的大树旁有个小卖铺

看了其他人的博客,根据需求写的:

要实现的效果就是,如果键盘遮住的输入框,那么要把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.接着实现通知触发事件

#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;

}
上一篇下一篇

猜你喜欢

热点阅读