以编程方式创建多个可拖动视图的最佳方法是什么?



我想要许多可拖动的标签,并编写了以下代码来实现这一点。然而,这是一种非常愚蠢的方法......因为我为每个对象编写了一个函数。有没有一种方法可以只使用一个函数来实现相同的效果?

override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel(frame: CGRectMake(UIScreen.mainScreen().bounds.width / 2 - 100, UIScreen.mainScreen().bounds.height / 2 - 100, 100, 50))
let label2 = UILabel(frame: CGRectMake(UIScreen.mainScreen().bounds.width / 2 - 100, UIScreen.mainScreen().bounds.height / 2 - 200, 100, 50))
label.text = "Str"
label.textAlignment = NSTextAlignment.Center
label.backgroundColor = UIColor.greenColor()
self.view.addSubview(label)
label2.text = "ing"
label2.textAlignment = NSTextAlignment.Center
label2.backgroundColor = UIColor.greenColor()
self.view.addSubview(label2)

let gesture = UIPanGestureRecognizer(target: self, action: Selector("wasDragged:"))
label.addGestureRecognizer(gesture)
label.userInteractionEnabled = true
let gesture2 = UIPanGestureRecognizer(target: self, action: Selector("wasDragged1:"))
label2.addGestureRecognizer(gesture2)
label2.userInteractionEnabled = true

}
func wasDragged(gesture: UIPanGestureRecognizer) {
let translation = gesture.translationInView(self.view)
if let label = gesture.view {
label.center = CGPoint(x: label.center.x + translation.x, y: label.center.y + translation.y)
}
gesture.setTranslation(CGPointZero, inView: self.view)

}
func wasDragged1(gesture:UIPanGestureRecognizer) {
let translation = gesture.translationInView(self.view)
if let label = gesture.view {
label.center = CGPoint(x: label.center.x + translation.x, y: label.center.y + translation.y)
}
gesture.setTranslation(CGPointZero, inView: self.view)

}

保持DRY原则干得好!

我要做的是制作一个名为Draggable的协议,该协议仅限于UIView- 因为UILabelUIView的子类,并且因为如果您愿意,您也可以稍后UIView拖动。

protocol Draggable where Self: UIView {}

然后,我将对Draggable协议进行扩展,其中包含设置UIPanGesture和处理其wasDragged回调等方法。

extension Draggable {
// Implement things to make the view draggable
}

然后,我将UILabel子类化为实现Draggable协议的CustomLabel

class CustomLabel : UILabel, Draggable {
// Customize your label here
}

在这里,您可以轻松看到此自定义标签是UILabel的一个子类,最重要的是,它是可拖动的!

extension UILabel {
convenience init(
text:String,
textAlignment:NSTextAlignment,
backgroundColor:UIColor,
target:Any,
action:Selector
)
{
self.init(frame:CGRect.zero)
self.text = text
self.textAlignment = textAlignment
self.backgroundColor = backgroundColor
if target != nil && action != nil {
let gesture = UIPanGestureRecognizer(target: target, action: #selector(action))
self.addGestureRecognizer(gesture)
}
}

您可以将此扩展设置为UILabel或UIView,以最适合您的方式为准。如果需要,可以使此方便的初始值设定项失败,并根据需要向其添加任何其他内容。(我更喜欢将初始帧设置为 CGRect.zero 但 YMMV。

最新更新