解决UIScrollView,UIImageView等控件不能响应touch事件的问题

时间:2020-12-07 21:27:08

关于UIScrollView,UIImageView等控件不能响应touch事件,主要涉及到事件响应者链的问题,如果在UIScrollView,UIImageView等控件添加了子View,这样事件响应将会被UIScrollView,UIImageView等控件终止,而且这些控件的userInteractionEnabled属性默认的是NO,所以想要解决使用触摸事件,我通过两种方法进行解决。

方法一:

创建UIScrollView,UIImageView等控件的类别文件,将touch的四个方法进行父类方法重写:(创建Objective-C File文件,然后修改类型,创建对应的类别文件)

#import "UIScrollView+TouchEvent.h"



@implementation UIScrollView (TouchEvent)



- (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] touchesEnded:touches withEvent:event];

    [super touchesEnded:touches withEvent:event];

}

@end

方法二:通过给UIScrollView,UIImageView等控件添加手势,执行对应的方法

如:

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    bgScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 200, 400)];

    bgScrollView.backgroundColor = [UIColor lightGrayColor];

//添加手势

UITapGestureRecognizer *tapGestureR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(updateImageVAction:)];

    [bgScrollView setUserInteractionEnabled:YES];

    [bgScrollView addGestureRecognizer:tapGestureR];

[self.view addSubview:bgScrollView];

    

    textFie = [[UITextField alloc] initWithFrame:CGRectMake(50, 50, 100, 50)];

    textFie.layer.borderWidth = 1;

    [bgScrollView addSubview:textFie];

    

}

//手势执行的方法

-(void)updateImageVAction:(UITapGestureRecognizer *)tapGR

{

    [textFie resignFirstResponder];

}