【问题标题】:Swift 3 Update the variable which represents the time interval between a function being calledSwift 3更新代表被调用函数之间的时间间隔的变量
【发布时间】:2017-03-25 13:19:33
【问题描述】:

我创建了一个函数,它每 27 秒调用一次。调用变量的代码如下

_ = Timer.scheduledTimer(timeInterval: time, target: self, selector: #selector(GameScene.method), userInfo: nil, repeats: true)

变量time在函数方法中乘以0.95,但变量time仍然没有更新。

【问题讨论】:

  • 检查该方法是否正在调用。
  • 对不起,你是什么意思?该方法正在被调用,但它每 27 秒调用一次,而不是变量的更新版本
  • 请告诉我们方法和它的代码。

标签: swift function time swift3 nstimer


【解决方案1】:

如果你想改变时间,你用scheduledTimer指定的timeInterval保持不变,如果你想改变时间,那么你需要像这样在调用函数中再次安排它。

 _ = Timer.scheduledTimer(timeInterval: time, target: self, selector: #selector(GameScene.method), userInfo: nil, repeats: false)

 func method() {
     //Do your task
     time += 0.95 //increase timer
     //Schedule it again
     _ = Timer.scheduledTimer(timeInterval: time, target: self, selector: #selector(GameScene.method), userInfo: nil, repeats: false)
 }

【讨论】:

  • 您需要先使计时器无效,否则每次方法调用都会有多个计时器。
  • @zisoft 检查正确我已将重复设置为 false'
  • 一个问题:它说不能将timer类型的值赋给int
  • @ArthurMacpherson 你从哪里得到这个?
【解决方案2】:
func increaseTime() {

   time += 0.95 // This will increase the time by 0.95 every time this function is called

   // Then call the function again to update the time
   _ = Timer.scheduledTimer(timeInterval: time, target: self, selector: #selector(GameScene.method), userInfo: nil, repeats: true)

}

确保您的变量是 var 而不是 letconst,因为无法编辑常量变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-06
    相关资源
    最近更新 更多