I’m sure this is a basic misunderstanding of the responder chain – has it changed since iOS4? I have a view with some subviews. The superview has no purpose other than positioning the subviews, and should have nothing to do with handling touches. I want the subviews to listen for touches, but the superview seems to block touch events. I thought superviews passed touches on to subviews? I’ve read several posts on this, but I can’t get my head around it. Several posts seem to suggest that setting userInteractionEnabled to NO for the superview will work, but doing this still doesn’t seem to let the touch through.
In case it’s not clear what I mean, here’s some simplified code. Tapping inside the red view does NOT trigger the NSLog…
@implementation ViewController
@synthesize redView;
- (void)viewDidLoad
{
UIView *blueView = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 200, 400)];
blueView.backgroundColor = [UIColor blueColor];
[self.view addSubview:blueView];
redView = [[UIView alloc]initWithFrame:CGRectMake(20, 20, 40, 40)];
redView.backgroundColor = [UIColor redColor];
[blueView addSubview:redView];
[super viewDidLoad];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint touchPoint = [touch locationInView:self.view];
if (CGRectContainsPoint(redView.frame, touchPoint)) {
NSLog(@"red got touched");
}
}
@end
The coordinates of the touch you are receiving are expressed in the coordinate system of the enclosing view. So you need to correct them with the offset of the blueView. One way would be to add a blueView property to your object and then correct in the touchesBegan method:
Or you could subclass UIView for the blueView and override touchesBegan there