John
John

Reputation: 63

How do I detect whenever two UIImageView overlap?

I have two UIImageViews, one of them is moving from left to right, the other one is touch draggable. iI want NSLog to show up a message on console whenever imagetwo overlaps imageone. How Do I do this?

Upvotes: 6

Views: 4029

Answers (4)

user3069232
user3069232

Reputation: 8995

In Swift 3.0 has become...

if (self.image2P.bounds.contains(self.image3P.bounds)) {
    print("Overlaped, it's working!")
}

Upvotes: 0

Chris Zelenak
Chris Zelenak

Reputation: 2178

You can use the CGRectIntersectsRect function to easily test rectangle intersection, provided the UIImageViews share the same superview (more exactly, have the same coordinate space).

Likely you will need to add code like the following:

  -(void) touchesEnded:(NSSet *) touches {
    if(CGRectIntersectsRect([imageViewA frame], [imageViewB frame])) {
      NSLog(@"Do something.");
    }
  }

to the UIView that hosts both image views, or a similar method that is called whenever the drag is completed.

Upvotes: 12

Rajender Kumar
Rajender Kumar

Reputation: 1377

try something like this.

if (CGRectContainsRect([myImageView1 frame], [myImageView2 frame])) {
        NSLog(@"Overlaped, it's working!");
}

Upvotes: 1

Max
Max

Reputation: 16719

You can use:

CGRectIsNull(CGRectIntersection(view1.bounds, view2.bounds));

Upvotes: 0

Related Questions