IOS UIImageView轻击手势没有响应
轻击手势总是在用,可是今天加在一个UIImageView上,这个手势竟然没有响应。
问题是这样的:
UIImageView *background = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"1.jpg"]]; background.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height); [self.view addSubview:background]; UIImageView *smallPad = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"0.png"]]; smallPad.frame = CGRectMake(20, 20, 30, 30); smallPad.userInteractionEnabled = YES; [background addSubview:smallPad]; UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(test)]; [smallPad addGestureRecognizer:tap];
注意,这个是我写的调试程序,很明显,一个底层的UIImageView加在self.view上,然后再在这个UIImageView上加东西,我这里是又加了一个UIImageView,然后给最上层的这个视图加了个轻击手势,并设置这个最上层视图的交互为YES!我觉得够了,但事情并没有按照我想的发展。
思考良久,终于明白了。改了:
我们只需要加一行代码,问题解决了:
[super viewDidLoad]; UIImageView *background = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"1.jpg"]]; background.userInteractionEnabled = YES; background.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height); [self.view addSubview:background]; UIImageView *smallPad = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"0.png"]]; smallPad.frame = CGRectMake(20, 20, 30, 30); smallPad.userInteractionEnabled = YES; [background addSubview:smallPad]; UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(test)]; [smallPad addGestureRecognizer:tap];
还记得事件派发和响应者链吗?这里就用到了这个原理。简单说一下,程序在派发事件的时候依据一定的层次结构,最上层是:程序代理delegate,接着是窗口window,再 接下来就是我们的视图,在给视图派发事件时,通过点击测试(hit-testing)来判断当前被测试视图是否具有交互能力,有交互能力才会派发事件。当用户轻击或者划动屏幕时,这时候就产生了事件,那么这个事件交给谁处理呢?这是我们上面说的,要调用hit-test:withEvent:方法,该方法递归的调用视图继承树中每个视图的pointInside:withEvent:方法并在其返回true后,从该视图开始沿着继承树向下,直到找到一个点击事件在其范围之内的子视图,这个视图就是hit-test视图。而如果当前被测试视图没有交互能力,这个hit-test:withEvent:根本就不会调用,这个视图及他的子视图都不会响应任何事件了。