专注iOS开发iOS精选移动开发

UIScrollView点击空白处退出键盘方法(含与键盘手写冲突

2016-05-30  本文已影响1878人  vincent涵

UIScrollView 上如果有UITextField的话,结束编辑(退出键盘)直接用touchesBegan方法无效,需要再给UIScrollView加一个分类,重写几个方法。
网上已经有很多前辈给了相关代码是这样的(阅前提示:这样是有问题的!):

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [[self nextResponder] touchesBegan:touches withEvent:event];
    [super touchesBegan:touches withEvent:event];
    
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    [[self nextResponder] touchesMoved:touches withEvent:event];
    [super touchesMoved:touches withEvent:event];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [[self nextResponder] touchesEnded:touches withEvent:event];
    [super touchesEnded:touches withEvent:event];
}

这样会有一个严重问题,就是使用手写输入法输入中文会导致崩溃(虽然使用手写输入法的人不多,但也不能无视他们)。被坑死,问题是百度出来尼玛80~90%全是这种解决方法。坑死人!

有一些前辈对于“UIScrollView点击空白处退出键盘”就提出了另一种解决方法:加一层view,给view一个点击事件,退出键盘。

但是我的项目中已经被前一种方法坑了,已经有用户反映手写崩溃,换第二种方法的话很麻烦,需要修改之后重新提交审核,不能及时解决,我需要及时的用JSPatch线上打补丁解决。调试了很久,我发现手写键盘在调用UIScrollView的这个分类的方法时,self的类型是UIKBCandidateCollectionView,一种系统没有暴露出来的类型,应该是UIScrollView的一个子类,所以解决办法就呼之欲出了,直接上代码。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    if (![self isMemberOfClass:[UIScrollView class]]) {
        
    } else {
        [[self nextResponder] touchesBegan:touches withEvent:event];
        if ([super respondsToSelector:@selector(touchesBegan:withEvent:)]) {
            [super touchesBegan:touches withEvent:event];
        }
    }
    
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    if (![self isMemberOfClass:[UIScrollView class]]) {
        
    } else {
        [[self nextResponder] touchesMoved:touches withEvent:event];
        if ([super respondsToSelector:@selector(touchesBegan:withEvent:)]) {
            [super touchesMoved:touches withEvent:event];
        }
    }
    
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    if (![self isMemberOfClass:[UIScrollView class]]) {
        
    } else {
        [[self nextResponder] touchesEnded:touches withEvent:event];
        if ([super respondsToSelector:@selector(touchesBegan:withEvent:)]) {
            [super touchesEnded:touches withEvent:event];
        }
    }
}

手写输入法崩溃完美解决O(∩_∩)O~~

上一篇 下一篇

猜你喜欢

热点阅读