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

时间:2016-12-07 00:39:41

标签: ios swift

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

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)



    }

2 个答案:

答案 0 :(得分:1)

保持 DRY 原则的好工作!

我要做的是将名为Draggable协议限制为UIView - 因为UILabelUIView的子类,因为如果你愿意的话,你可以稍后让UIView拖延。

protocol Draggable where Self: UIView {}

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

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

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

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

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

答案 1 :(得分:0)

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