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