Swift 3标签通过触摸移动

时间:2017-05-25 13:33:42

标签: ios swift swift3 label uigesturerecognizer

多个标签,我想通过触摸移动 我只是想让你在我创建的视图中移动

enter code here
@IBOutlet weak var cardView: UIView!
@IBOutlet weak var label1: UILabel!
@IBOutlet weak var label2: UILabel!
@IBOutlet weak var label3: UILabel!



override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let position = touch.location(in: self.cardView)
        print(position.x, position.y)
        label.frame.origin = CGPoint(x:position.x-60,y:position.y-30)
    }
}

2 个答案:

答案 0 :(得分:1)

要在其超级视图中移动标签,您可以将UIPanGestureRecognizer添加到标签。 例如

func setGesture() -> UIPanGestureRecognizer {
    var panGesture = UIPanGestureRecognizer()
    panGesture = UIPanGestureRecognizer (target: self, action: #selector("handlePan:"))
    panGesture.minimumNumberOfTouches = 1
    panGesture.maximumNumberOfTouches = 1
    return panGesture
}
//set the recognize in multiple views
lbl1.addGestureRecognizer(setGesture())
lbl2.addGestureRecognizer(setGesture())

答案 1 :(得分:0)

对于用手指移动物体,覆盖touchesMoved方法就足够了。您在示例中遗漏的内容是,您应该从当前previousLocation解除location。以下是示例代码:

class MovableView: UIView {

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        let oldLocation = touches.first?.previousLocation(in: self)
        let newLocation = touches.first?.location(in: self)
        move(with: CGPoint(x: (newLocation?.x)! - (oldLocation?.x)!, y: (newLocation?.y)! - (oldLocation?.y)!))

    }

    private func move(with offset: CGPoint) {
        center = CGPoint(x: center.x + offset.x, y: center.y + offset.y)
    }

}