Search code examples
swift3drag-and-dropuipangesturerecognizernested-if

drag and drop UIView inside another (UIPanGesture recognizer)


I am trying to drag a UIView on the screen to be inside another UIView i'm comparing their frames while drag-drop to check if (bead1 matches hole1 in frames) i can drag and drop just fine , but the problem is when i drag (bead2 to hole 2) bead1 automatically is placed in hole1 (like the second IF in the code becomes true) please help here's the function:

func draggingView(_ sender: UIPanGestureRecognizer){

let point = sender.location(in: view)
let draggingView = sender.view!
draggingView.center = point
print(point)
   if sender.state == .ended && bead1.frame.midX  != 
hole1.frame.midX  {
            print("false")
            bead1.center = CGPoint (x: view.frame.width / 2 - 25, y: 
  view.frame.height / 2)
           }
     if sender.state == .ended && bead1.frame.midX  == 
           hole1.frame.midX {
         bead1.center = hole1.center
         imageToShow.isHidden = false
        // sender.isEnabled = false
        print("True")
       }

  if sender.state == .ended && bead2.frame.minX - 10 != 
   hole2.frame.minX - 10{
    print("false")
    bead2.center = CGPoint (x: view.frame.width / 2 + 25, y: 
 view.frame.height / 2)
  }
 if sender.state == .ended && bead2.frame.minX - 10 == hole2.frame.midX 
 - 10{ 
 bead2.center = hole2.center
         imageToShow.isHidden = false
        // sender.isEnabled = false
        print("True")

  } 

 } 

Solution

  • i could finally fix it .. I actually needed to check if a UIView contains another UIView then to compare each UIView with another's tag (I needed to set a tag to each and every UIView) like the following..

        hole1.tag = 1
         bead1.tag = 1
         if hole1.tag == bead1.tag{
             print("Bead1 IS IN!")
    
         }else{
            print("bead1 IS OUT!!!!")
      }
    

    and then check if it contains other's center

     if bead1.frame.contains(hole1.center)