NSTimer以延迟显示背景颜色

时间:2015-09-20 10:49:59

标签: swift nstimer

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

struct

2 个答案:

答案 0 :(得分:1)

您正在if语句中设置shareAlert.presentViewController(shareAlert, ...)

您应该将yourCurrentViewController.presentViewController(shareAlert, ...) 移到if语句之外但仍在for循环中。因此,获取self.gameButton.setBackgroundColor(color)后面的self.gameButton.setBackgroundColor(color)并将其粘贴到}前面。

答案 1 :(得分:0)

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

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