iosswiftdelayincrementanimatewithduration

Incrementing a parameter in UIView.animateWithDuration in Swift


I have an IBOutlet Collection of buttons that I am trying to present on screen sequentially. They all start off screen fine, but as they animate in, I'd like each button to be presented on screen 0.05 seconds after the previous button. I can't figure out how to increment the delay in UIView.animateWithDuration. With the code below, they are all animating on screen at the same time.

//outlet collection
@IBOutlet var options: [UIButton]!

let increment = 0.25

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    for button in options {
        button.center.y += view.bounds.height
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    for button in options {
        UIView.animateWithDuration(1.0, delay: increment, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.0, options: nil, animations: {
            button.center.y -= self.view.bounds.height
            self.increment + 0.05
            }, completion: nil)
    }
}

Solution

  • for button in options {
            UIView.animateWithDuration(1.0, delay: increment, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.0, options: nil, animations: {
                button.center.y -= self.view.bounds.height
                }, completion: nil)
    
        }
               increment = increment + 0.05
    
    }
    

    Besides: Change this

    let increment = 0.25
    

    To

       var increment = 0.25
    

    Increase the increment outside animation. Because animateWithDuration is an async method,it will return first. So,all your button have same delay.