How can I make a function execute every second in swift?

后端 未结 7 1762
离开以前
离开以前 2020-11-29 01:59

I want to add a score to the top of my scene in the game I am working on. The score is going to based on how long you last, and will increase every second. Thanks for the he

7条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 02:39

    There is something called NSTimer in swift which could solve your problem. I have given an example like how you can use it. Just customise it for your purpose.

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

    Add this line to the place where you need to call your function repeatedly.

    1. The 1.0 refers to 1 second.
    2. Change the selector to call yourMethodName
    3. repeats is set to true to call that function every second.

    Try this out and let me know if your are stuck somewhere. Thanks.

提交回复
热议问题