我有AutoLayout,所以它总是会重新定位图像到原来的位置。我需要更新允许AutoLayout执行此操作的约束条件。然后我的图像能够在屏幕上移动。 我为自己的形象(newX,newY)获得了新的位置,并将其设置为我的新约束条件。
// Set up outlets from the image's constraints in the Storyboard
@IBOutlet weak var leadingConstraint: NSLayoutConstraint!
@IBOutlet weak var topConstraint: NSLayoutConstraint!
// Set a new Leading (X) and Top (Y) constraints for the image
let newLeadingConstraint = NSLayoutConstraint(item: happyFace, attribute: .Leading, relatedBy: .Equal, toItem: self.view, attribute: .Leading, multiplier: 1.0, constant: newX)
let newTopConstraint = NSLayoutConstraint(item: happyFace, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1.0, constant: newY)
// Remove the old image constraints and set the new ones (ie move the image)
self.view.removeConstraint(leadingConstraint)
self.view.removeConstraint(topConstraint)
self.view.addConstraint(newLeadingConstraint)
self.view.addConstraint(newTopConstraint)
self.view.layoutIfNeeded() // Force the layout before drawing
leadingConstraint = newLeadingConstraint
topConstraint = newTopConstraint