1

I am new to swift and xcode. using xcode 10 and trying to make a buzzle like app where i need to move several images in the view. I found a lot about UIPanGestureRecognizer and UITapGestureRecognizer but all are working for the UIImage that has the last addGestureRecognizer only not for the rest.

Is there a way to detect which UIImage that i am touching to enable its movement?

Kaushik Makwana
  • 1,329
  • 2
  • 14
  • 24
Ahmed Amer
  • 21
  • 4

2 Answers2

1
  1. For every image view, add a tag (if necessary maintain dictionary of tags and images)
  2. In your gesture recogniser, get the image view on which user touches.
  3. Get that view's tag to identify image view and identify the image accordingly.
Satyam
  • 15,493
  • 31
  • 131
  • 244
1

I found a solution or actually what i was doing wrong:

You need to define a new variable of UIPanGestureRecognizer for each UIImage the variable is controlling one object at a time.

Thank you

This is what worked

@IBOutlet var imagesToMove: [UIImageView]!


let imagesNames = ["chk", "unchk"]

var gesturePanArray: [UIPanGestureRecognizer] = []
var gestureTapArray: [UITapGestureRecognizer] = []

override func viewDidLoad() {
    super.viewDidLoad()
    var i = 0

    for imageItem in imagesToMove {
        imageItem.image = UIImage(named: imagesNames[0])

        imageItem.isUserInteractionEnabled = true
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(self.wasDragged(_:)))
        gesturePanArray.append(panGesture)
        imageItem.addGestureRecognizer(gesturePanArray[i])

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.wasTouched(_:)))

        gestureTapArray.append(tapGesture)
        imageItem.addGestureRecognizer(gestureTapArray[i])

        i = i + 1
    }

}

@objc func wasDragged(_ gesture: UIPanGestureRecognizer) {
    let translation = gesture.translation(in: self.view)
    let image = gesture.view

    view.bringSubviewToFront(image!)

    image!.center = CGPoint(x: (image?.center.x)! + translation.x, y: (image?.center.y)! + translation.y)
    gesture.setTranslation(CGPoint.zero, in: self.view)

}

@objc func wasTouched (_ gesture: UITapGestureRecognizer) {

    let imageTag = gesture.view?.tag
    if imagesToMove[imageTag! - 1].image == UIImage(named: imagesNames[0]) {
    imagesToMove[imageTag! - 1].image = UIImage(named: self.imagesNames[1])
    } else {
     imagesToMove[imageTag! - 1].image = UIImage(named: self.imagesNames[0])
    }
}

}

Ahmed Amer
  • 21
  • 4