Search code examples
swiftaddsubview

adding animation when creating multiple subviews in swift


I am having a problem animating my buttons as I create them using addsubview. They all show up at once even when I increase the delay of the animation in my loop. I would be grateful to anyone that can help.

func createButton () {
    var setx = 50
    var sety = 100
    var delay = 0.4
    var wordsInCharacters = [String]()
    for letter in "RAILROAD".characters{
        wordsInCharacters.append("\(letter)")
    }
    while wordsInCharacters.count > 0 {
        let randomIndex = Int(arc4random_uniform(UInt32(wordsInCharacters.count)))
        // Creating the buttons
        let button = SpringButton()
        button.frame = CGRect(x: setx, y: sety, width: 64, height: 64)
        button.setTitle( "\(wordsInCharacters[randomIndex])", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.backgroundColor = UIColor.gray
        button.titleLabel?.font = UIFont(name: "HelveticaNeue", size: 30)
        // Add animation
        UIView.animate(withDuration: 1, delay: delay, options: .curveEaseInOut, animations: {
            self.view.addSubview(button)
        }, completion: nil)
        if setx <= 200 {
            setx += 100
        }
        else{
            setx = 50
            sety += 100
        }
        wordsInCharacters.remove(at: randomIndex)
        delay += 0.2

    }
}

Solution

  • for making a easy animation dont add the views in the animation block. At first set the Button Alpha value to 0, than add the button as subview. In the animationblock u set the button.alpha to 1. Voila ...