0

I have 10 buttons on my story board and their current states are hidden.

Based on certain condition I want to display those 10 buttons, but I want to put 1 sec. delay between them

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

    }

I guess one way is to use NSTimer but not sure how that will work in the loop? Can someone help me with this?

Thanks Borna

borna
  • 906
  • 3
  • 12
  • 32
  • possible duplicate of [@selector() in Swift?](http://stackoverflow.com/questions/24007650/selector-in-swift) – Jeff Jul 26 '15 at 00:03

2 Answers2

0

You need to switch gears from batch programming to event-driven programming.

You need a state variable (stored property) in your UIViewController class that keeps track of the array index of the button.

You then start a timer, perhaps during viewDidAppear():

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

then you implement your target action appropriately:

func handleTimer(timer: NSTimer) {
    buttons[buttonIndex++].hidden = false
    if buttonIndex == buttons.count {
        timer.invalidate()
    }
}
BaseZen
  • 8,650
  • 3
  • 35
  • 47
0

There are a few ways to do this, what I would probably start with is to create a property for which button index is next, and a function to do the work you want. In the function, you dispatch_after to call the function again. Here is a quick and dirty example of what I mean:

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

Then in viewDidLoad you call showNextButton()

Good Doug
  • 2,072
  • 15
  • 12