2015-09-09 104 views
0

我有一个UIImage(happyFace),当用户点击屏幕时,我正在屏幕上移动。我还有一个计数器(tapLabel),每次点击图像时都会更新一次。 当我注释掉tapLabel.text的更新时,图像在屏幕上移动。 当我更新tapLabel.text时,图像保持原位,但其X和Y坐标更新。我正在使用AutoLayout,但对UIImage没有限制。奇怪...坐标更新后图像不刷新

// Assign the image's new position and update counter label 
    happyFace.frame.origin.x = CGFloat(newX) 
    happyFace.frame.origin.y = CGFloat(newY) 

    tapLabel.text = String(tapCount) 

我在想什么?

回答

0

我有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