Why doesn't this sleep feature work when I try to revive the rain?

This is my code:

@IBAction func click(sender: UIButton) {
    for var x = 0; x<100; ++x{
        r1.center.y += 0.2
        usleep(10000)
    }
}

      

I am using Swift in Xcode 7.0 beta. I used UIButton

to test it and simplify it to one raindrop. When I click, I want it to move smoothly (as best as possible) downward.

Right now, it just waits for all the functions usleep(10000)

(100 of them) to finish so that it doesn't move for 1 second, and then it moves 20 pixels down. Am I using the function sleep()

( usleep()

actually) incorrectly, or do I need to use a different type of wait function to get the animation to work correctly?

It's worth mentioning that I don't get any errors when running the code in the simulator.

+3


source to share


1 answer


The user interface is updated only when program control returns to the main event loop. Therefore, your changes to r1.center

become visible only when the method returns click()

.

Also you block the main thread for a long time, which is usually bad because no events are being processed and the UI is not updated, so the application becomes unresponsive. Blocking the main thread for too long can cause the program to be killed by the OS.



Instead, you can use a timer with a callback function that updates the position.

Alternatively (as pointed out in the comment), use Core Animation .

+3


source







All Articles