swift 拖动按钮_ios – Swift:实现可拖动的UIImageView需要哪些方法?

本文介绍了如何在Swift中创建可拖动的UIImageView,通过实现UIPanGestureRecognizer来追踪触摸并移动图片视图。代码示例展示了初始化和触摸事件处理过程,同时也提到了一个常见错误:忘记设置`userInteractionEnabled = true`。
摘要由CSDN通过智能技术生成

如标题中所述,我希望用户能够拖动UI

ImageView作为图片上的图钉,我已经按照

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, 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)

}

...

}

当我启动应用程序时,一切都正确显示,但如果我试图拖动它们,引脚不会移动.我恐怕错过了什么……你知道吗?

也许这个方法触及了’sMoved()但是在教程中没有提到……

最佳答案 更新:回答

愚蠢我,我错过了

self.userInteractionEnabled = true

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值