SWIFT无限动画/函数调用循环

时间:2016-05-01 18:30:02

标签: ios swift loops animation while-loop

我正在构建一个模拟Conway生命游戏的应用程序。我按下RUN按钮时尝试运行无限动画。这是我的代码:

//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按钮时,我想要调用run(),它应该每3秒连续调用runrepeat()。 board.run()运行算法来确定下一代单元格的配置,而forButton {}循环则更新所有单元格的外观。

然而,按原样,runrepeat()只被调用一次,因此下一代出现在棋盘上并且动画停止,没有任何延迟。我的RUN按钮正确执行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)
        }
    }
  }

但是无限循环只会导致我的程序冻结。屏幕的更新永远不会发生。

有人可以帮我执行连续函数调用,屏幕更新循环吗?请在4天内到期。

1 个答案:

答案 0 :(得分: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
    }
}

然后,您可以每3秒调用一次UI更新,如下所示:

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