2017-05-25 96 views
0

多個標籤,我想通過觸摸 動我只是希望你在視圖中移動我創建斯威夫特3個標籤通過觸摸移動

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) 
    } 
} 
+0

我不知道你的問題是什麼:( –

+0

此代碼的工作,但我希望做一個以上的標籤,所以它僅適用於LABEL1 –

+0

創建標籤的數組,循環遍歷它們?或者通過包含標籤的視圖中的子視圖進行循環,例如,'parentView.subviews中的標籤{//完成您的事情}' –

回答

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()) 
+0

您是否有示例代碼 –

0

對於用手指移動的物體,它足以覆蓋touchesMoved方法。在你的例子中你錯過的東西是你應該從當前的location中破壞previousLocation。下面是一個示例代碼:

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

}