gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 19:34:26 24 4
gpt4 key购买 nike

如标题所述,我希望用户能够拖动用作图片图钉的 UIImageView,我已关注 this教程。这是我写的类(class):

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
}

}

那些 pin UIImageViews 应该移动到包含 UIViewController 的更大的 UIImageView 上:

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() 但是教程中没有提到...

最佳答案

更新:回答

愚蠢的我,我错过了

self.userInteractionEnabled = true

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

关于ios - Swift:实现可拖动的 UIImageView 需要哪些方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33824260/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com