【问题标题】:Swift: which methods are needed to implement a draggable UIImageView?Swift:实现可拖动的 UIImageView 需要哪些方法?
【发布时间】:2016-02-22 19:08:54
【问题描述】:

正如标题中所说,我希望用户能够拖动 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()的方法,但是教程中没有提到...

【问题讨论】:

  • 将您的更新发布为答案,以便我们“将其标记为已完成”
  • 好的,我马上去

标签: ios iphone swift uiimageview draggable


【解决方案1】:

更新:回答

我傻了,我错过了

self.userInteractionEnabled = true

init() 方法中,我以为它们是默认启用的。

【讨论】:

  • 这个错误很容易理解,因为 UIView 的默认值 userInteractionEnabled 是 true。 UIImageView 的文档说:New image view objects are configured to disregard user events by default. If you want to handle events in a custom subclass of UIImageView, you must explicitly change the value of the userInteractionEnabled property to YES after initializing the object.
  • 一些有用的东西要记住,因为我需要很多其他的东西。谢谢你:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-26
  • 2014-12-19
  • 2013-02-26
  • 2013-04-10
  • 1970-01-01
  • 2015-01-11
  • 2019-11-13
相关资源
最近更新 更多