Swift: what methods are needed to implement a dragged UIImageView?

As the title says, I would like the user to be able to drag and drop the UIImageView, which serves to display the image, and I followed this tutorial. Here is the class I wrote:

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
}

}

These contacts UIImageViewsshould move on a larger one UIImageView, which contains 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 application, everything displays correctly, but the contacts do not move if I try to drag them. I'm afraid I'm missing something ... do you know what? Maybe a method touchedìsMoved(), but it is not mentioned in the textbook ...

+4
1

:

,

self.userInteractionEnabled = true

init(), , .

+2

Source: https://habr.com/ru/post/1616711/


All Articles