2015-09-28 48 views
0

如何在按下时移动按钮?如何移动UIButtons?

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { 
    if let touch = touches.first { 
     location = touch.locationInView(self.view) 
     Button.center = location 
    } 
    super.touchesBegan(touches, withEvent:event) 
} 
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { 
    if let touch = touches.first { 
     location = touch.locationInView(self.view) 
     Button.center = location 
    } 
    super.touchesMoved(touches, withEvent:event) 
} 

该按钮不动。

回答

0

如果您使用AutoLayout放置按钮,则必须更新确定按钮位置的约束条件。

这通常是通过将约束暴露给IBOutlet并修改它的constant属性(它实际上并不是常数)来完成的。

您将需要两个约束:

  • 水平距离从UIView
  • 垂直距离左侧从顶部的你UIView

例如顶部

horizontalConstraint.constant = location.x 
verticalConstraint.constant = location.y 

如果你不使用自动版式(即您使用自动尺寸/弹簧和支柱),那么你上面的代码应该只是工作。因此,您可以尝试在视图的xib中关闭AutoLayout。