gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:27:37 26 4
gpt4 key购买 nike

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

//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() 运行算法来确定下一代单元的配置,并且 for cellButton{} 循环更新所有单元的外观。

但是,按照原样,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)
}
}
}

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

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

最佳答案

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
})

关于ios - SWIFT 无限动画/函数调用循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36970365/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com