【问题标题】:Changing UILabel text causes movable UIImageView objects to revert back to original position更改 UILabel 文本会导致可移动 UIImageView 对象恢复到原始位置
【发布时间】:2014-11-02 21:38:23
【问题描述】:

我创建了一个带有多个可移动(使用平移手势识别器)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 文本时从它们的随机位置恢复到它们的默认故事板位置。

【问题讨论】:

  • 这很奇怪......所以你是说当你删除最后一行“timerLabel.text!=”Timer:......”时,一切正常?
  • 是的,如果我把它注释掉就可以了。 UIImageView 不会改变位置。
  • 自动布局正在运行并重新定位您的对象。关闭自动布局。
  • @vacawama 解决了!谢谢!如果您将其添加为答案,我将向您抛出已接受的解决方案。

标签: ios swift uiimageview uilabel nstimer


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-29
    • 2020-06-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    相关资源
    最近更新 更多