SWIFT Updating screen in between steps of while lo

2020-05-06 04:59发布

I'm building an app that simulates Conway's Game Of Life. I'm trying to run an infinite animation when a RUN button is pressed. Here's my code:

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

When the RUN UI button is pressed, I want run() to be called, which should continuously call runrepeat() every 3 seconds. board.run() runs algorithms to determine the configuration of the next generation of cells, and the for cellButton{} loop updates that appearances of all the cells.

However, as is, runrepeat() is only called once, so the next generation appears on the board and the animation stops, without any delays. My RUN button is correctly executing runrepeat(), but only once. I want it to repeat forever.

I tried this too:

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

but the infinite while loop just causes my program to freeze up. The updating of the screen never happens.

Can someone please help me with executing a continuous function call, screen update loop?

标签: swift loops
0条回答
登录 后发表回答