【问题标题】:Xcode NSTimer count++Xcode NSTimer 计数++
【发布时间】:2015-11-18 18:24:42
【问题描述】:

我有一个 NSTimer 在名为 moving 的函数中每 0.05 秒运行一次。 在moving 里面我想要一个数字来计数并显示到标签中 同时让一个物体移动。

现在的问题是它只能同时做其中一件事情。 这是代码:

timer = NSTimer.scheduledTimerWithTimeInterval(0.05, target: self, selector: "moving", userInfo: nil, repeats: true)    

func moving() {

   countingUp = countingUp + 1

    label.text = "\(countingUp)"

    objectOne.center = CGPointMake(objectOne.center.x, objectOne.center.y + 1) 
}

现在它只是在对象不移动时在标签中计数。 但是,如果我删除标签的整个代码部分,则对象正在移动。 有人可以帮我解决这个问题吗?

【问题讨论】:

  • 你可能需要在主线程上运行代码,

标签: xcode swift nstimer


【解决方案1】:

试试这个:

let runloop = NSRunLoop.currentRunLoop()
let timer = NSTimer(timeInterval: 0.05, target: self, selector: "moving", userInfo: nil, repeats: true)
runloop.addTimer(timer, forMode:NSRunLoopCommonModes)
runloop.addTimer(timer, forMode:UITrackingRunLoopMode)

【讨论】:

    【解决方案2】:

    试试这个...

        let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(0.05 * Double(NSEC_PER_SEC)))
    dispatch_after(delayTime, dispatch_get_main_queue()) {
     countingUp = countingUp + 1
     label.text = "\(countingUp)"
     objectOne.center = CGPointMake(objectOne.center.x, objectOne.center.y + 1)
    }   
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-10
      • 1970-01-01
      • 1970-01-01
      • 2010-11-10
      相关资源
      最近更新 更多