Vasily Vasily - 1 year ago 117
iOS Question

Check if view within other view?

I’m using UIPanGestureRecognizer to move UIImageView. Now i’m need to check if user moved my object within other vectored-PDF UIImageView.

For example we have red bar that we are moving and we need to move red bar inside blue bar (blue bar is vector PDF). How can we check that?

Example image:

Example code:

@IBAction func moveRedBox(recognizer: UIPanGestureRecognizer) {
let translation = recognizer.translationInView(self.view)
recognizer.view!.center = CGPoint(x:recognizer.view!.center.x + translation.x,
y:recognizer.view!.center.y + translation.y)
recognizer.setTranslation(CGPointZero, inView: self.view)

if recognizer.state == UIGestureRecognizerState.Ended {
// Here we will check that redBox inside blueBox

Answer Source

To check if two view's overlap you can use the CGRectIntersectsRect function.

Update: Just found out that there is also an intersects method on CGRect in Swift

let doRectsIntersect = rect1.intersects(rect2) 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download