iOS swift 和计时器

iOS swift and timer

我的故事板上有 10 个按钮,它们的当前状态是隐藏的。

基于特定条件,我想显示这 10 个按钮,但我想放置 1 秒。他们之间的延迟

    for button in buttons {   // there are 10 buttons
        button.hidden = false;
        button.setBackgroundImage(UIImage(named: "MyImage"), forState: UIControlState.Normal)
        // delay 1 sec

    }

我想一种方法是使用 NSTimer 但不确定它在循环中如何工作? 有人可以帮我解决这个问题吗?

谢谢 博尔纳

您需要从批处理编程切换到事件驱动编程。

您的 UIViewController class 中需要一个状态变量(存储 属性)来跟踪按钮的数组索引。

然后您启动一个计时器,也许在 viewDidAppear() 期间:

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    buttonIndex = 0
    timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "handleTimer:", userInfo: nil, repeats: true)
}

然后你适当地实施你的目标行动:

func handleTimer(timer: NSTimer) {
    buttons[buttonIndex++].hidden = false
    if buttonIndex == buttons.count {
        timer.invalidate()
    }
}

有几种方法可以做到这一点,我可能首先会创建一个 属性 用于下一个按钮索引,以及一个函数来完成您想要的工作。在函数中,你dispatch_after再次调用函数。这是我的意思的一个快速而肮脏的例子:

var currentButton = 0
func showNextButton() {
        if currentButton < buttons.count {
            buttons[currentButton].hidden = false
            buttons[currentButton].setBackgroundImage(UIImage(named: "MyImage"), forState: UIControlState.Normal)
            currentButton++
            // delay 1 second
            let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC)))
            dispatch_after(delayTime, dispatch_get_main_queue()) {
                self.showNextButton()
            }
        }
    }

然后在 viewDidLoad 你调用 showNextButton()