Vasily
Vasily

Reputation: 3790

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: https://i.sstatic.net/7pVZA.png

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
    }
}

Upvotes: 2

Views: 2764

Answers (3)

Teodor Ciuraru
Teodor Ciuraru

Reputation: 3477

Check this out. This helped me:

if view1.frame.contains(view2.center) {
    // do your thing
  }

Full example:

@IBAction func moveRedBox(recognizer: UIPanGestureRecognizer) {

  ...

  switch recognizer.state {

  case .Ended:

    if blueBox.frame.contains(recognizer.view!.center) {
      print("Yep")
    }
  }

}

Upvotes: 1

Jawwad
Jawwad

Reputation: 1336

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) 

Upvotes: 2

Hazem
Hazem

Reputation: 178

Check position of UIImageView

image.frame.origin.x >= view.frame.origin.x
image.frame.origin.y >= view.frame.origin.y

put this code when the movement done

Upvotes: 0

Related Questions