Oleksandr Matrosov
Oleksandr Matrosov

Reputation: 27191

Detecting intersection of two UIView objects at different superview

I've got a problem with detecting intersection of my UIView objects.

That's what I have used below:

For intersection two object I need to figure out how to translate one coordinates system from first superview to another coordinates system.

I've used this approach: - (CGRect)convertRect:(CGRect)rect fromView:(UIView *)view described here link.

As I know it is very simple to use this method. But in the different cases it is hard due a little description in documentation (but maybe just for me).

This is my structure of subviews that is shown on image below. I have already got all methods for drag and drop object. But I need to figure out how to get intersection for UIView A and UIView B. Thanks for help.

enter image description here

Upvotes: 9

Views: 2201

Answers (2)

rob mayoff
rob mayoff

Reputation: 385998

I think this is equivalent to the code in your answer, but considerably shorter:

- (void)putComponent:(NSNotification *)note {
    UIView *other = note.object;
    CGPoint otherCenterInMe = [self convertPoint:other.center fromView:other.superview];
    if ([self pointInside:otherCenterInMe withEvent:nil]) {
        NSLog(@"intersect here");
    }
}

Upvotes: 0

Oleksandr Matrosov
Oleksandr Matrosov

Reputation: 27191

I have implemented this solution:

- (void)putComponent:(NSNotification *)notif {
    // Catch B UIView.
    UIView *view = [notif object];
    // Convertation. [self superview] - is view wher A UIView is placed.
    CGRect convertedRect = [[self superview] convertRect:view.frame fromView:[view superview]];
    // Find center point.
    CGPoint point;
    point.x = convertedRect.origin.x + (convertedRect.size.width / 2.0f);
    point.y = convertedRect.origin.y + (convertedRect.size.height / 2.0f);
    // Find if CGRect (self.frame) contains a point (center of B UIView)
    BOOL contains = CGRectContainsPoint(self.frame, point);
    if (contains) {
        NSLog(@"intersect here");
    }
}

Upvotes: 6

Related Questions