Reputation: 5427
As said in title, I would like the user to be able to drag a UIImageView which serves as pin on a picture and I have followed this tutorial. Here's the class I have written:
import UIKit
class PinImageView: UIImageView {
var lastLocation:CGPoint?
var panRecognizer:UIPanGestureRecognizer?
init(imageIcon: UIImage?, location:CGPoint) {
super.init(image: imageIcon)
self.lastLocation = location
self.panRecognizer = UIPanGestureRecognizer(target:self, action:"detectPan:")
self.center = location
self.gestureRecognizers = [panRecognizer!]
self.frame = CGRect(x: location.x, y: location.y, width: 20.0, height: 30.0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func detectPan(recognizer:UIPanGestureRecognizer) {
let translation = recognizer.translationInView(self.superview!)
self.center = CGPointMake(lastLocation!.x + translation.x, lastLocation!.y + translation.y)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
// Promote the touched view
self.superview?.bringSubviewToFront(self)
// Remember original location
lastLocation = self.center
}
}
Those pin UIImageViews
should move upon a larger UIImageView
which is contained UIViewController
where:
class PhotoViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet weak var imageView: UIImageView!
var imagePicker: UIImagePickerController!
var redLocationA:PinImageView = PinImageView(imageIcon: UIImage(named: "pin1.png"), location: CGPointMake(80, 330))
var redLocationB:PinImageView = PinImageView(imageIcon: UIImage(named: "pin1.png"), location: CGPointMake(80, 360))
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(redLocationA)
self.view.addSubview(redLocationB)
}
...
}
When I launch the app everything is correctly showed but the pins do not move if I try to drag them. I am afraid I am missing something...do you know what?
Maybe the method touchedìsMoved()
but it's not mentioned in the tutorial...
Upvotes: 4
Views: 1826
Reputation: 5427
UPDATE: answer
Stupid me, I missed
self.userInteractionEnabled = true
inside the init()
method, I thought they were enabled by default.
Upvotes: 3