iOS键盘的监听,以及处理遮挡问题

iOS开发中经常会使用到键盘,因此简单介绍下

通知的添加

#pragma mark 键盘的处理
//添加通知来监听键盘
- (void)addKeyboardNotification{
    //通知中心
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    //键盘出现通知
    [center addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    //键盘隐藏通知
    [center addObserver:self selector:@selector(keyBoardWillHidden:) name:UIKeyboardWillHideNotification object:nil];
    
}

这里仅仅移动,可用于textField等

#pragma mark 这里仅仅移动,可用于textField等
//键盘的出现
- (void)keyBoardWillShow:(NSNotification *)noti
{
    //1.获取到系统键盘的高度
    CGFloat keyboardH = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    //2.获取键盘出现的时间
    CGFloat duration = [noti.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //3.添加键盘位移的动画
    [UIView animateWithDuration:duration animations:^{
            //4.发生位移
            self.view.transform = CGAffineTransformMakeTranslation(0,  -keyboardH );
    }];
}

//键盘的隐藏
- (void)keyBoardWillHidden:(NSNotification *)noti{
    //1.获取键盘消失的时间
    CGFloat duration = [noti.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //2.添加动画,并且是位置恢复原位
    [UIView animateWithDuration:duration animations:^{
        self.view.transform = CGAffineTransformIdentity;
    }];
}

如果textField有滑动的话,可以调用下面方法是键盘隐藏

//继承与UIScrollView的都可以调用这个方法
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

移动,有可能发生遮挡的处理,可用于登陆的处理

#pragma mark 移动,有可能发生遮挡的处理,可用于登陆的处理
//键盘的出现
- (void)keyBoardWillShow:(NSNotification *)noti
{
    // 1.取得当前聚焦文本框最下面的Y值
    CGFloat loginBtnMaxY = CGRectGetMaxY(loginBtn.frame);
    // 2.取出键盘的高度
    CGFloat keyboardH = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    // 3.控制器view的高度 - 键盘的高度
    CGFloat keyboardY = self.view.frame.size.height - keyboardH;
    // 4.比较登录按钮最大Y 跟 键盘Y
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //5.隐藏bug的处理
    if (duration <= 0.0) {
        duration = 0.25;
    }
    
    [UIView animateWithDuration:duration animations:^{
        if (loginBtnMaxY > keyboardY) { // 键盘挡住了登录按钮
            self.view.transform = CGAffineTransformMakeTranslation(0, keyboardY - loginBtnMaxY - 8);
        } else { // 没有挡住登录按钮
            self.view.transform = CGAffineTransformIdentity;
        }
    }];
}

//键盘的隐藏
- (void)keyBoardWillHidden:(NSNotification *)noti
{
//获取动画时间
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //恢复默认位置
    [UIView animateWithDuration:duration animations:^{
        self.view.transform = CGAffineTransformIdentity;
    }];
}

键盘上enter按钮的点击

//enter按钮
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    NSLog(@"haha");
    return YES;
}

最后在结束的时候记得销毁通知

//销毁通知
- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

你可能感兴趣的:(iOS键盘的监听,以及处理遮挡问题)