更改UILabel文本会导致可移动的UIImageView对象恢复到原始位置

时间:2014-11-02 21:38:23

标签: ios swift uiimageview uilabel nstimer

我创建了一个故事板,其中包含多个可移动(使用平移手势识别器)UIImageView对象,默认情况下是隐藏的。我有一个UIButton,当按下时,会为要移动的按钮生成随机的X和Y位置,如下所示:

// Places each puzzle piece at a random location on the screen
for puzzlePiece in puzzlePieces {

        // Generate a random X position for the new center point of the puzzle,
        // so that the piece is on the screen. Must convert to UInt and then CGFloat
        var randomXPosition: CGFloat = CGFloat(UInt(114 + arc4random_uniform(796)))

        // Generate a random Y position for the new center point of the puzzle,
        // so that the piece is on the screen. Must convert to UInt and then CGFloat.
        var randomYPosition: CGFloat = CGFloat(UInt(94 + arc4random_uniform(674)))

        puzzlePiece.frame = CGRect(x: randomXPosition, y: randomYPosition, width: puzzlePiece.frame.width, height: puzzlePiece.frame.height)
}

UIImageViews移动到随机位置后,它们将被取消隐藏,显示计时器的UILabel开始跟踪时间,如下所示:

timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateTimerLabel"), userInfo: nil, repeats: true)

问题在于,只要NSTimer调用“updateTimerLabel”方法并修改了UILabel's文本,所有UIImageViews都会恢复为指定的默认位置在故事板上(加上由于平移而导致的任何转换)。具体来说,此方法的最后一行会导致问题:

func updateTimerLabel() {

    secondsElapsed++;

    var numSecondsToDisplay = secondsElapsed % 60
    var numMinutesToDisplay = ((secondsElapsed - numSecondsToDisplay) % 3600) / 60
    var numHoursToDisplay = (secondsElapsed - numSecondsToDisplay - numMinutesToDisplay) / 3600

    var secondsToDisplay = String(format: "%02d", numSecondsToDisplay)
    var minutesToDisplay = String(format: "%02d", numMinutesToDisplay)
    var hoursToDisplay = String(format: "%02d", numHoursToDisplay)

    timerLabel.text! = "Timer: \(hoursToDisplay):\(minutesToDisplay):\(secondsToDisplay)"
}

我想知道在更改UIImageViews文字时是否有任何方法可以阻止UILabel's从其随机位置恢复到默认的故事板位置。

1 个答案:

答案 0 :(得分:2)

自动布局正在运行并重新定位对象。关闭“自动布局”,您的对象将保留在放置它们的位置。