I am programmatically generating several UIButtons and then animating them with a block animation. I am able to determine which button was touched by implementing the code in this answer (demonstrated below).
My issue now is that the images can overlap, so when there is more than 1 view at the given touch location, my code in touchesBegan pulls out the wrong button (i.e., gets the image underneath the visible button that I’m touching).
I wanted to use [touch view] to compare to the UIButtons on screen:
if (myButton==[touch view]) { ...
But that comparison always fails.
My touchesBegan:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint touchLocation = [touch locationInView:self.view];
for (UIButton *brain in activeBrains) {
//Works, but only when buttons do not overlap
if ([brain.layer.presentationLayer hitTest:touchLocation]) {
[self brainExplodes:brain];
break;
}
/* Comparison always fails
if (brain == [touch view]) {
[self brainExplodes:brain];
break;
}
*/
}
}
So my question is how can I determine which of the overlapping images is above the other(s)?
I made a few assumptions here in my code here, but essentially you need to get a list of all the Buttons that have been touched and then find the one ‘on top’. The one on top should have the highest index of the buttons in the array of subviews.
Also, I typed this in the edit window so please excuse typos.