坐标更新后图像不刷新

时间:2015-09-09 16:13:52

标签: ios uiimage

我有一个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)

我错过了什么?

1 个答案:

答案 0 :(得分: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