Reputation: 16168
I have to do some "snap to grid" behaviour,
I have a dragging image "sprite", but I need to "snap" this sprite to a certain button if touches go on top of that button,
so how can i know if touchesEnded is on top of a certain button, here my code, but i dont know when touches where ended on top of butotn
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touched = [[event allTouches] anyObject];
CGPoint location = [touched locationInView:touched.view];
CGRect recta = touched.view.frame;
if (CGRectIntersectsRect(recta, self.button_1.frame)) {
DLog(@"intersected");
}
}
So this is not happening, can it be done?
or do i have to check the X and Y position of finishing touch against the button frame X and Y position by my self?
cheers
Upvotes: 1
Views: 174
Reputation: 781
touched.view is the view on which the touch started. You want to find out if the location where the touch ended is on top of a specific button. You can do this by checking if the location of the touch relative to the button is within the button's bounds.
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touched = [[event allTouches] anyObject];
CGPoint locationRelative = [touched locationInView:self.button_1];
if (CGRectContainsPoint(self.button_1.bounds, locationRelative)) {
DLog(@"on top of button_1");
}
}
Upvotes: 1
Reputation: 104082
You can use CGRectIntersectsRect, which returns YES, if the two rectangles your pass to it intersect.
Upvotes: 1