Swift:实现可拖动的UIImageView需要哪些方法?

时间:2015-11-20 10:23:53

标签: ios iphone swift uiimageview draggable

如标题中所述,我希望用户能够拖动UIImageView作为图片上的图钉并且我已经按照this教程。这是我写的课程:

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
}

}

这些图钉UIImageViews应移动到UIImageView更大的UIViewController,其中包含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) } ... } ,其中:

touchedìsMoved()

当我启动应用程序时,所有内容都正确显示但如果我尝试拖动它们,则引脚不会移动。我恐怕错过了什么......你知道吗? 也许方法([G|I|R|F])([0-9]{1,4})/g 但是在教程中没有提到......

1 个答案:

答案 0 :(得分:2)

更新:回答

愚蠢的我,我错过了

self.userInteractionEnabled = true

init()方法中,我认为默认情况下已启用它们。