我想要许多可拖动的标签,并编写了以下代码来实现这一点。然而,这是一种非常愚蠢的方法......因为我为每个对象编写了一个函数。有没有一种方法可以只使用一个函数来达到同样的效果?
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
- 因为 UILabel
是UIView
的子类,因为如果您愿意,您可以稍后将 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/