TIMEX
TIMEX

Reputation: 271614

How can I animate my View Controller's background to fade among multiple colors?

How can I do that without causing infinite memory issues? I'm trying something like this:

override func viewDidAppear(animated: Bool) {
        view.backgroundColor = UIColor.whiteColor()
        fadeBackground()
    }

    let colors = [UIColor.blueColor(), UIColor.redColor(), UIColor.greenColor(), UIColor.orangeColor(), UIColor.purpleColor()]
    func fadeBackground(){
        UIView.animateWithDuration(4, delay: 0, options: UIViewAnimationOptions.CurveLinear, animations: {
            var randomIndex = Int(arc4random_uniform(UInt32(self.colors.count)))
            self.view.backgroundColor = self.colors[randomIndex]
        }) { (stuff Bool) -> Void in
            self.fadeBackground()
        }
    }

I'm afraid this will eventually eat up the memory. How can I do this without recursion? Do I need [unowned self] ?

Upvotes: 3

Views: 453

Answers (1)

Schemetrical
Schemetrical

Reputation: 5536

I believe that's the right code. Try setting view.backgroundColor to an initial color like UIColor.whiteColor() and try again. Then you can randomly pick another color with arc4random() or something and call the same method.

Upvotes: 2

Related Questions