天天看點

解決UIScrollView,UIImageView等控件不能響應touch事件的問題

關于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];

}