2016-05-01 50 views
0

我正在构建一个模拟康威生命游戏的应用程序。我试图在按下RUN按钮时运行无限动画。这里是我的代码:SWIFT无限动画/函数调用循环

//When RUN button is clicked, call run repeat 
    @IBAction func run(sender: AnyObject) { 
     UIView.animateWithDuration(3, delay: 2, options: [.Repeat], animations: {self.runrepeat()}, completion: nil) 
} 

//Run repeat calls run, calculating next generation of the board 
func runrepeat() { 
     board.run() 
     //Update the appearance of all the buttons based on their new values 
     for cellButton in self.cellButtons { 
      cellButton.setTitle("\(cellButton.getLabelText())", 
       forState: .Normal) 
    } 
} 

当按下RUN UI按钮,我想运行每3秒()被调用,应不断呼叫runrepeat()。 board.run()运行算法来确定下一代单元的配置,for cellButton {}循环更新所有单元的外观。

但是,runrepeat()仅被调用一次,所以下一代出现在板上,动画停止,没有任何延迟。我的运行按钮正确执行runrepeat(),但只有一次。我希望它永远重复。

我想这太:

//Run repeat calls run, calculating next generation of the board 
    func runrepeat() { 
      while(true){ 
      board.run() 
      //Update the appearance of all the buttons based on their new values 
      for cellButton in self.cellButtons { 
       cellButton.setTitle("\(cellButton.getLabelText())", 
        forState: .Normal) 
     } 
    } 
    } 

但无限while循环只是使我的程序冻结。屏幕的更新从未发生过。

有人可以帮我执行一个连续的函数调用,屏幕更新循环?请在4天内付清。

回答

0
extension NSTimer { 
    static public func schedule(delay delay: NSTimeInterval, handler: NSTimer! -> Void) -> NSTimer { 
     let fireDate = delay + CFAbsoluteTimeGetCurrent() 
     let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, 0, 0, 0, handler) 
     CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes) 
     return timer 
    } 

    static func schedule(repeatInterval interval: NSTimeInterval, handler: NSTimer! -> Void) -> NSTimer { 
     let fireDate = interval + CFAbsoluteTimeGetCurrent() 
     let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, interval, 0, 0, handler) 
     CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes) 
     return timer 
    } 
} 

然后,你可以调用UI每3秒更新,像这样:

NSTimer.schedule(repeatInterval: 3.0, handler: { timer in 
    //UI updates 
})