美文网首页
一款超轻量级的iOS键盘自适应组件,支持TextField、Te

一款超轻量级的iOS键盘自适应组件,支持TextField、Te

作者: 南城琉璃月 | 来源:发表于2018-09-26 10:21 被阅读0次

    效果展示

    demo.gif

    使用方式

    (考虑到并不是每个页面中都需要加入自适应输入框的,一个项目中实际上需要也较少,按需加入更合适,节省内存占用)

    - (void)viewDidLoad {
        [super viewDidLoad];
        [KeyBoardObserver autoScrollWithTargetView:_textField scrollView:_scrolllview];
        [KeyBoardObserver autoScrollWithTargetView:_textView scrollView:_scrolllview];
    }
    

    其中 _textField和_textView是需要加入键盘自适应的实例对象,_scrolllview是它们的父级视图

    实现原理

    实现的代码也很少,不超过50行,已实现自动释放,支持随用随取,用完释放。

    + (void)autoScrollWithTargetView:(UIView*)targetView scrollView:(UIScrollView*)scrollView{
        KeyBoardObserver *sinton = [KeyBoardObserver new];
        sinton.targetView = targetView;
        sinton.sv = scrollView;
        objc_setAssociatedObject(targetView, associatedKey, sinton, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        [[NSNotificationCenter defaultCenter] addObserver:sinton selector:@selector(keyBordDidShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:sinton selector:@selector(keyBordDidHide:) name:UIKeyboardWillHideNotification object:nil];
    }
    
    - (void)keyBordDidHide:(NSNotification*)noti{
        _responseScrollView = nil;
        if (_sv && _targetView && self.isCurrentKeyboardTarget) {
            [UIView animateWithDuration:0.3 animations:^{
                self->_sv.contentOffset = CGPointMake(0, _tableViewOriYOffset);
            }completion:^(BOOL finished) {
                self.isCurrentKeyboardTarget = NO;
            }];
        }
    }
    
    - (void)keyBordDidShow:(NSNotification*)noti{
        
        if (_responseScrollView != self.sv) {
            _tableViewOriYOffset = _sv.contentOffset.y;
            _responseScrollView = self.sv;
        }
        
        if (_sv && _targetView && [_targetView isFirstResponder]) {
            self.isCurrentKeyboardTarget = YES;
            CGRect keyBoardBounds = [[[noti userInfo]objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
            
            UIWindow* window = [UIApplication sharedApplication].keyWindow;
            CGRect windowFrame = [_targetView.superview convertRect:_targetView.frame toView:window];
            
            if (keyBoardBounds.origin.y <= (windowFrame.origin.y+windowFrame.size.height)) {
                CGFloat offsetY = windowFrame.origin.y + windowFrame.size.height - keyBoardBounds.origin.y;
                [_sv setContentOffset:CGPointMake(0, _sv.contentOffset.y + offsetY) animated:YES];
            }
        }
    }
    
    - (void)dealloc{
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    

    最后附 demo下载

    相关文章

      网友评论

          本文标题:一款超轻量级的iOS键盘自适应组件,支持TextField、Te

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