您好,欢迎来到二三四教育网。
搜索
您的当前位置:首页【Objective-c】 键盘遮挡问题解决

【Objective-c】 键盘遮挡问题解决

来源:二三四教育网

整体过程如下:
1、监听键盘获取键盘高度
2、计算输入框(UITextView和UITextField)的需调整的位移量
3、恢复视图原来的位置

@property (nonatomic, assign) CGFloat keyBoardHeight;   //键盘高度
@property (nonatomic, assign) CGRect originalFrame;    //记录视图的初始坐标
@property (nonatomic,strong) UITextView *currentTextView;   //当前输入框
1、监听键盘
#pragma-mark KeyboardNotification
-(void)viewWillAppear:(BOOL)animated{
    [self registerForKeyboardNotifications];
    [super viewWillAppear:animated];
}
//取消注册(必须)
-(void)viewWillDisappear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super viewWillDisappear:animated];
}
//注册
- (void)registerForKeyboardNotifications{
    //使用NSNotificationCenter 鍵盤出現時
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification object:nil];
    //键盘消失时
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
2、通过textView和textField的代理方法获取输入框对象,并记录视图初始位置frame,这里以textView为例子
#pragma-mark textFieldDelegate
-(void)textViewDidBeginEditing:(UITextView *)textView{
    self.currentTextView = textView;
    self.originalFrame = self.view.frame;
}
3、计算视图self.view需要移动的偏移量
- (void)keyboardWillShow:(NSNotification*)notification{
    NSDictionary* info = [notification userInfo];
    //kbSize即為鍵盤尺寸 (有width, height)
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;//得到鍵盤的高度
    _keyBoardHeight = kbSize.height;

    //第一步:将textField的坐标转换为相对整个屏幕的坐标值
    
    CGFloat controlY = [textView convertRect:currentTextView.bounds toView:[UIApplication sharedApplication].keyWindow].origin.y;
    //第二步:计算偏移值公式:(10是为了效果加上去的,可以自定义)
    //(屏幕高度 - 键盘高度)- (输入框的新坐标值Y + 输入框高度 + 10)
    CGFloat controlHeight = currentTextView.bounds.size.height;
    CGFloat offset = (SCREEN_H - _keyBoardHeight) - (controlY + controlHeight+10);
    CGFloat offsetY;
    //第三步:判断
    //如果输入框不会被键盘遮挡(offset>0)就保存原来的坐标就好
    if (offset>0) {
        offsetY = self.view.frame.origin.y;
    }else{
        offsetY = offset;
    }
    //设置视图移动的位移
    self.view.frame = CGRectMake(self.view.frame.origin.x,offsetY, self.view.frame.size.width, self.view.frame.size.height);

}
    
4、键盘消失恢复视图位置
//键盘消失恢复视图位置
- (void)keyboardWillHide:(NSNotification *)notification{
    CGFloat duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
       self.view.frame = self.originalFrame;
    }];
}

Copyright © 2019- how234.cn 版权所有 赣ICP备2023008801号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务