Swift NSTimer以延迟方式显示背景色

Swift NSTimer以延迟方式显示背景色,swift,nstimer,Swift,Nstimer,试图让它延迟显示背景色,但它跳到了最后一个。我认为计时器会在每次迭代之前留出时间。我错过了什么 func displayLevel() { status.setText("Watch the sequence.") color = UIColor() for (value, number) in gameArray.enumerate() { if value == 0 {

试图让它延迟显示背景色,但它跳到了最后一个。我认为计时器会在每次迭代之前留出时间。我错过了什么

func displayLevel() {

        status.setText("Watch the sequence.")

            color = UIColor()

            for (value, number) in gameArray.enumerate() {

                if value == 0 {
                    color = UIColor.redColor()
                } else if value == 1 {
                    color = UIColor.greenColor()
                } else if value == 2 {
                    color = UIColor.blueColor()
                } else if value == 3 {
                    color = UIColor.yellowColor()

                self.gameButton.setBackgroundColor(color)

            }

        }

    }

    func startTimer() {

        timer = NSTimer.scheduledTimerWithTimeInterval(speed, target: self, selector: "displayLevel", userInfo: nil, repeats: false)

    }

您正在if语句中设置self.gameButton.setBackgroundColor(color)


您应该将
self.gameButton.setBackgroundColor(color)
移到if语句外部,但仍在for循环内部。因此,在
self.gameButton.setBackgroundColor(color)
后面获取最后一个
,并将其粘贴在
self.gameButton.setBackgroundColor(color)

前面。如果希望根据计时器间隔显示颜色,则需要设置一个重复计时器。然后每次更改颜色时都会调用
displayLevel()
。为下一个循环增加
,然后在到达终点时使计时器无效:

class ViewController: UIViewController {

    var value = 0
    var timer: NSTimer?
    let speed = 0.5

    func startTimer() {
        value = 0
        timer = NSTimer.scheduledTimerWithTimeInterval(speed, target: self,
            selector: "displayLevel", userInfo: nil, repeats: true)
    }

    func displayLevel() {
        let color: UIColor

        switch value {
        case 0: color = .redColor()
        case 1: color = .greenColor()
        case 2: color = .blueColor()
        default:
            color = .yellowColor()

            // We've reached the last color.  Turn off the timer.
            timer?.invalidate()
        }

        self.gameButton.backgroundColor = color

        // increment value for next go around
        value++
    }
}

self.gameButton.setBackgroundColor(颜色)这应该在最后一个else if块之外