键盘的监听

1、监听
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];/**< 键盘将要出现的通知 */
    
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillDismiss:) name:UIKeyboardWillHideNotification object:nil];/**< 键盘将要消失的通知 */
2、touchesBegan:让键盘在点击视图的时候收起来
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    //键盘消失
    [self.password resignFirstResponder];/**< 让某一个textFlies或者textView 键盘消失 */
    
    //从输入源的父视图消失
    [self.view endEditing:YES];/**< 让父视图上面的原件的键盘消失 */
    
}
2、键盘的移动
#pragma mark --  键盘监听
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [_bgview  removeFromSuperview];
   [self.view endEditing:YES];/**< 让父视图上面的原件的键盘消失 */
}
- (void)keyBoardWillShow:(NSNotification *)notification {
    _bgview = [[UIView alloc]initWithFrame:self.view.frame];
    [self.view addSubview:_bgview];
   
    //获取第一相应者
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    UIView *firstResponder = [keyWindow performSelector:@selector(firstResponder)];
    UIView *view = [firstResponder superview];
    //获取键盘的frame
    
    CGRect keyboardRect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
 
    if (keyboardRect.origin.y < CGRectGetMaxY(view.frame)) {
        //获取键盘出现的时间
        NSTimeInterval interal = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
        //计算 视图应该移动的位置
        CGFloat offset =  CGRectGetMaxY(view.frame) - keyboardRect.origin.y ;
        
        [UIView animateWithDuration:interal animations:^{
            self.view.bounds = CGRectMake(0, offset, kWidth, self.view.frame.size.height);
            self.navigView.center =CGPointMake(self.view.center.x, 32 + offset);
            
        }];
    }
}
- (void)keyboardWillDismiss:(NSNotification *)notification {
    
    [_bgview  removeFromSuperview];
 //获取键盘消失的时间
 NSTimeInterval interal = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
 
    
    [UIView animateWithDuration:interal animations:^{
        self.view.bounds = CGRectMake(0, 0, kWidth, self.view.frame.size.height);
        self.navigView.center =CGPointMake(self.view.center.x, 32 );
    }];
    
    
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容