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

标签 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)



    }

最佳答案

很好地遵守了 DRY 原则!

我要做的是制作一个名为 Draggable协议(protocol),它仅限于 UIView - 因为 UILabelUIView 的子类,因为如果您愿意,您可以稍后将 UIView 设为可拖动。

protocol Draggable where Self: UIView {}

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

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

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

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

在这里,您可以很容易地看到这个自定义标签是 UILabel 的子类,最重要的是,它是 Draggable!

关于ios - 以编程方式制作多个可拖动 View 的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41007490/

相关文章:

ios - 在 NSString 中查找与另一个字符的位置相关的字符的位置

ios - UITableView 删除按钮不会对手势使用react

ios - 单张照片上的 3d 触摸。 iOS, swift

ios - 如何将按钮链接到操作

ios - Swift 删除选项和不必要的字符 iOS

ios - 当新条目出现时,如何从右到左为标签内的文本设置动画?

ios - 无法从阵列中获取正确的音频文件来播放

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

ios - 为什么不将值user.username传递给导航器

ios - 无法在 Xcode 中连接 IBAction