美文网首页
iOS 处理键盘弹出的通用框架BaseViewControlle

iOS 处理键盘弹出的通用框架BaseViewControlle

作者: 晨寂 | 来源:发表于2017-12-20 15:30 被阅读0次

    最近写了一个项目,遇到需要处理键盘弹出/收起时,避免键盘遮挡输入框的问题。
    所以当时我写了一个BaseViewController框架(可以用来当做所有ViewController的基类),在BaseViewController设置属性判断是否需要处理键盘,并且处理了当键盘第一次弹出时会出现中文键盘高度不对的问题。


    github地址:https://github.com/WalkingToTheDistant/KeyboardHandle/tree/master,如果觉得我写的代码对你有帮助的话,给我一个星呗^ _ ^


    使用方法

    设置基类BaseViewController或者其子类的属性isNeedHandleKeyboard为YES(默认NO),这个变量必须在BaseViewController的ViewDidLoad执行之前设置,因 为在BaseViewController的ViewDidLoad里面会执行检索代码,给所有输入框添加键盘关闭栏。

    /** 是否需要处理键盘弹出/收起的事件,默认NO */
    @property(nonatomic, assign) BOOL isNeedHandleKeyboard;
    

    代码解析

    首先是添加监听,这里的逻辑,就是用_isNeedHandleKeyboard来判断这个ViewController是否需要处理键盘

    
    @interface BaseViewController ()
    
    /** 是否需要处理键盘弹出/收起的事件,默认NO */
    @property(nonatomic, assign) BOOL isNeedHandleKeyboard;
    
    /** 键盘弹出时,需要移动的高度值 */
    @property(nonatomic, assign) int moveValueForKeyboard;
    
    @end
    - (void) viewWillAppear:(BOOL)animated
    {
        [super viewWillAppear:animated];
        
        if(_isNeedHandleKeyboard == YES){ // 添加键盘监听
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardShow:) name:UIKeyboardWillShowNotification object:nil];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardHide:) name:UIKeyboardWillHideNotification object:nil];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardFrameChange:) name:UIKeyboardWillChangeFrameNotification object:nil]; // 监听键盘尺寸的变化
        }
    }
    
    - (void) viewWillDisappear:(BOOL)animated
    {
        [super viewWillDisappear:animated];
        
        if(_isNeedHandleKeyboard == YES){ // 消除键盘监听
            [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
            [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
            [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
        }
    }
    

    接下来处理键盘弹出/收起的事件

    // ****************************************************************************************************
    // ****************************************************************************************************
    #pragma mark - 键盘处理
    - (void) handleKeyboardShow:(NSNotification*) notification
    {
        if(_moveValueForKeyboard > 0){ // 键盘已经处理过,避免在键盘输入的时候再点击了其他的输入框
            return;
        }
        
        CGRect keyboardFrame = [[[notification userInfo] valueForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
        const float duration = [[[notification userInfo] valueForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
        const UIViewAnimationOptions options = [[[notification userInfo] valueForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
        
        UIView *viewFirst = [[self class] getFirstResponder:self.view];
        if(viewFirst != nil){
            
            CGPoint pointView = [viewFirst convertPoint:self.view.bounds.origin toView:self.view];
            pointView.y += CGRectGetHeight(viewFirst.frame);
            _keyboardHeight = CGRectGetHeight(keyboardFrame);
            int originYForKeyboard = CGRectGetMaxY(self.view.frame) - _keyboardHeight;
            
            if(pointView.y >= originYForKeyboard){ 
                // 输入框被键盘遮挡
                _moveValueForKeyboard = pointView.y - originYForKeyboard;
                __block CGRect frame = self.view.frame;
                frame.origin.y -= _moveValueForKeyboard;
                
                [UIView animateWithDuration:duration delay:0 options:options animations:^{
                    self.view.frame = frame;
                } completion:nil];
            } else {
                _moveValueForKeyboard = 0;
            }
        }
    }
    - (void) handleKeyboardHide:(NSNotification*)notification
    {
        if(_moveValueForKeyboard > 0){
            const float duration = [[[notification userInfo] valueForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
            const UIViewAnimationOptions options = [[[notification userInfo] valueForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
            
            __block CGRect frame = self.view.frame;
            frame.origin.y += _moveValueForKeyboard;
            _moveValueForKeyboard = 0;
            
            [UIView animateWithDuration:duration delay:0 options:options animations:^{
                self.view.frame = frame;
            } completion:nil];
        }
    }
    - (void) handleKeyboardFrameChange:(NSNotification*)notification
    {
        /* 在这里处理中文键盘的高度变化问题,在第一次弹出键盘之后,键盘上随后会展现中文的智能检测栏,导致键盘的高度会变高,而在UIKeyboardWillShowNotification得到的高度缺不包含这个监测栏的高度,从而输入框位置会被键盘遮挡。所以需要在这里监听键盘尺寸的变化,然后再计算尺寸变化值并修改输入框的位置。*/
        CGRect keyboardFrame = [[[notification userInfo] valueForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
        if(_moveValueForKeyboard > 0){ // 需要处理中文键盘的尺寸变化问题
            int valueChange = CGRectGetHeight(keyboardFrame) - _keyboardHeight;
            if(valueChange != 0){
                const float duration = [[[notification userInfo] valueForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
                const UIViewAnimationOptions options = [[[notification userInfo] valueForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
                __block CGRect frame = self.view.frame;
                frame.origin.y -= valueChange;
                _moveValueForKeyboard += valueChange;
                _keyboardHeight = CGRectGetHeight(keyboardFrame);
                [UIView animateWithDuration:duration delay:0 options:options animations:^{
                    self.view.frame = frame;
                } completion:nil];
            }
            
        }
    }
    

    这些事件处理需要一个方法辅助,一个是获取当前键盘输入的控件,然后再获取其相对屏幕的坐标,用以判断它是否被键盘给遮挡了

    /** 获取当前键盘输入的控件 */
    + (UIView*) getFirstResponder:(UIView*)superView
    {
        if(superView.isFirstResponder == YES){
            return superView;
        }
        
        for(UIView *viewChild in superView.subviews){
            if([viewChild isFirstResponder] == YES){
                return viewChild;
            }
        }
        // 再搜索下一层Subview
        for(UIView *viewChild in superView.subviews){
            UIView *viewResult = [[self class] getFirstResponder:viewChild];
            if(viewResult != nil){
                return viewResult;
            }
        }
        return nil;
    }
    

    在键盘上方添加关闭栏的通用方法。

    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view.
        if(_isNeedHandleKeyboard == YES){
            [self addDoneKeyboardViewToInputView:self.view];
        }
    }
    /** 创建键盘关闭的View */
    + (UIView*) getKeyboardHideViewWithTarget:(id)target withSelector:(SEL)selector
    {
        UIView *viewResult = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(UIScreen.mainScreen.bounds), 40)];
        [viewResult setBackgroundColor:RGBColor(250, 250, 250)];
        
        int height = CGRectGetHeight(viewResult.frame);
        int width = 80;
        int x = CGRectGetMaxX(viewResult.frame) - width;
        int y = 0;
        UIButton *btnDone = [UIButton buttonWithType:UIButtonTypeSystem];
        [btnDone setTitle:@"完成" forState:UIControlStateNormal];
        [btnDone.titleLabel setFont:Font_Bold(16.0f)];
        [btnDone setFrame:CGRectMake(x, y, width, height)];
        [btnDone addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];
        [viewResult addSubview:btnDone];
        
        return viewResult;
    }
    /** 给所有输入框的键盘都添加关闭 */
    - (void) addDoneKeyboardViewToInputView:(UIView*) superView
    {
        //这个方法可能是有效率问题,因为需要遍历整个ViewController的view,暂时还想不到更好的方法
        for(UIView *viewChlid in [superView subviews]){
            if([viewChlid isKindOfClass:[UITextField class]] == YES){
                if([viewChlid inputAccessoryView] == nil){
                    UIView *viewDone = [[self class] getKeyboardHideViewWithTarget:self withSelector:@selector(closeKeyboard)];
                    [((UITextField*)viewChlid) setInputAccessoryView:viewDone];
                }
                
            } else if([viewChlid isKindOfClass:[UITextView class]] == YES){
                if([viewChlid inputAccessoryView] == nil){
                    UIView *viewDone = [[self class] getKeyboardHideViewWithTarget:self withSelector:@selector(closeKeyboard)];
                    [((UITextView*)viewChlid) setInputAccessoryView:viewDone];
                }
            } else {
                [self addDoneKeyboardViewToInputView:viewChlid];
            }
        }
    }
    /** 关闭ViewController的键盘 */
    - (void) closeKeyboard
    {
        [self.view endEditing:YES];
    }
    

    相关文章

      网友评论

          本文标题:iOS 处理键盘弹出的通用框架BaseViewControlle

          本文链接:https://www.haomeiwen.com/subject/knmgwxtx.html