使用ScrollView时,点击事件会被ScrollView拦截,在有些情况下这会影响其它功能的实现.所以往往需要对这种情况处理,有时可以粗暴设置UserInteractionEnabled为NO,但这样会导致ScrollView上的按钮等视图也无法响应点击. 以上,所以就有了本文的产生. 示意图:
使用UIScrollView+UITouch.h前 点击黄色ScrollView和白色view,不会走控制器的"touchesBegan:withEvent:"方法
使用UIScrollView+UITouch.h后 点击ScrollView和view,都会走"touchesBegan:withEvent:"方法
@implementation InfoViewController - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { NSLog(@"点击View"); [self.view endEditing:YES]; } // 点击按钮 - (IBAction)tapButtonAction:(id)sender { UIButton *tempBut = (UIButton *)sender; if (tempBut.tag == 1000) { NSLog(@"点击Button"); [self.view endEditing:YES]; } } @endUIScrollView+UITouch
#import "UIScrollView+UITouch.h" @implementation UIScrollView (UITouch) - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { // 下面两句任选其一即可 [super touchesBegan:touches withEvent:event]; // [[self nextResponder] touchesBegan:touches withEvent:event]; } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesMoved:touches withEvent:event]; //[[self nextResponder] touchesMoved:touches withEvent:event]; } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesEnded:touches withEvent:event]; //[[self nextResponder] touchesEnded:touches withEvent:event]; } @end