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

后端 未结 7 1781
离开以前
离开以前 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:40

    I prefer

    var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()          
    
        timer =  Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (timer) in                
            // Do what you need to do repeatedly         
        }
    }
    

    To stop it:

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    
        if timer != nil {
            timer?.invalidate()
            timer = nil
        }
    }
    

提交回复
热议问题