Search code examples
iosswiftuiviewpan

Pan UImage within superview swift


I'm attempting to move an UIImageView within its superview using the pan gesture, although I'm able to make the superview move within self.view I am not able to do move one of its subviews within itself.

These are the relevant lines in my code

let couponOutline = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 424))

let imageView = UIImageView(image: UIImage(named: "ImagePlaceHolder"))
imageView.frame = CGRect(x: 0, y: 0, width: 128, height: 128)
imageView.center = CGPoint(x: 230, y: 300)

couponOutline.addSubview(imageView)
self.view.addSubview(couponOutline)

let panRec = UIPanGestureRecognizer(target: self, action: "moveView:")
    panRec.minimumNumberOfTouches = 1
    imageView.addGestureRecognizer(panRec)

in the moveView: method

func moveView(sender: UIPanGestureRecognizer) {

    println("pan")

    let couponOutline = view.subviews[0] as! UIView

    print(couponOutline)

    var translation = sender.translationInView(self.view)

    sender.view?.center = CGPoint(
        x: sender.view!.center.x + translation.x,
        y: sender.view!.center.y + translation.y)

    sender.setTranslation(CGPoint(x: 0, y: 0), inView: couponOutline)

I'm trying to move imageView within couponOutline, when I use this code it does not pick of the gesture at all (println("pan") is no shown).


Solution

  • A scroll view wouldn't be useful for some of the features I plan to add, I finally found the solution - All I needed to do was set imageView.userInteractioEnabled = true .