UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Multiple scheduled UI updates don't work

Forums > Swift

I am trying to make an image "move down" every second while also showing a time counter. I have a scheduledTimer where I change the image's Y center and update the timer. The timer label updates but the image does not move. Strangely I can get the image to move down if I comment the line where I update the timer's UILabel. So appearently I can't update both.

class ViewController: UIViewController {

    let starImage = UIImageView(image: UIImage(systemName: "star.fill"))
    let timerLabel = UILabel()
    var counter = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .black

        setupViews()
        gameEngine()
    }

    private func setupViews() {
        // SETTING LAYOUT CONSTRAINTS HERE -- not relevant for this issue
        ...
    }

    // PROBLEM HERE
    private func gameEngine() {
        Timer.scheduledTimer(withTimeInterval: 1, repeats: true) {
            [weak self] _ in
            self?.counter += 1
            self?.timerLabel.text = "Timer: \(self!.counter)"
            self?.starImage.center.y += 1
        }
    }

}

I tried adding the timer to the RunLoop, but I get the same results. I also tried doing it on a separated DispatchQueue. Any help will truly appreciated.

3      

Answering my own question all I had to do was to keep a reference to the topConstraint of the image so I could update it everytime it was supposed to move down.

   // Declare constraint
    var starImageTopConstraint: NSLayoutConstraint!

    // Later when setting constraints
    starImageTopConstraint = starImage.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: -30)

     NSLayoutConstraint.activate([
        ...
        starImageTopConstraint,
        ...
      ])

    // When I wish to move the image down by X
    starImageTopConstraint.constant += X

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.