关于UIScrollView无法处理UITouch事件

最近在工作中遇到一个问题,我在UIScrollView添加子控件UITextField,但是无法在-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event方法中实现UITextField 的resignFirstResponder隐藏键盘的事件。测试打断点之后发现,当我在触摸视图上空白的地方的时候,UITouch方法并没有运行,在网上一查,原来是UIView的touch事件被UIScrollView捕获。
然后,只需要给UIScrollView写一个类扩展,让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];
}

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

然后就在需要用的地方导入头文件,然后再在上面的方法里面操作就可以了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容