Search code examples
iosswiftuiimageviewuilabelnstimer

Changing UILabel text causes movable UIImageView objects to revert back to original position


I have created a storyboard with multiple movable (using pan gesture recognisers) UIImageView objects, that are hidden by default. I have a UIButton, that when pressed, generates random X and Y positions for the buttons to be moved to as follows:

// 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)
}

After the UIImageViews are moved to random positions, they are un-hidden, and a UILabel displaying a timer begins to keep track of time, as follows:

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

The problem is that whenever the NSTimer calls the "updateTimerLabel" method and the UILabel's text is modified, ALL of the UIImageViews revert to their default location as specified on the Storyboard (plus any transformations as a result of panning). Specifically, the last line of this method causes the issue:

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)"
}

I'm wondering if there is any way to prevent the UIImageViews from reverting from their random positions to their default Storyboard positions when changing the UILabel's text.


Solution

  • Auto Layout is running and repositioning your objects. Turn off Auto Layout and your objects will stay where you put them.