Search code examples
iosobjective-ccgrect

How to check intersections buttons


I'm dynamically creating buttons on UIView. I can move them by dragging using this code

- (IBAction)draggedOut: (id)sender withEvent: (UIEvent *) event: (NSSet *)touches {
   UIButton *selected = (UIButton *)sender;
   selected.center = [[[event allTouches] anyObject] locationInView:hallView];
}

I can have more then one button. When I'm dragging some button, I need to check are there any intersections with other buttons?

How can I do this?


Solution

  • You should cycle through the other buttons in the view and, for each of them, check whether in intersect the dragged one via:

    CGRectIntersectsRect (draggedButton.frame, anotherButton.frame);
    

    You could use a function like:

    - (BOOL)isThereButtonsIntersectionInView:(UIView *)containerView 
                                   forButton:(UIButton *)draggedButton
    {
        for(UIView *view in containerView.subviews){
            if([view isKindOfClass:[UIButton class]] &&
                view != draggedButton &&
                CGRectIntersectsRect (view.frame, draggedButton.frame)){
    
                    return YES;
                }
            }
        }
    
        return NO;
    }
    

    Call this method passing as a parameter the view containing the buttons and the dragged button.