最近在工作中遇到一个问题,我在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];
}
然后就在需要用的地方导入头文件,然后再在上面的方法里面操作就可以了。