Josh
Josh

Reputation: 743

iOS Swift - Changing background colours

I am trying to make the background colour cycle through different colours.

I found the code to do it in objective-c here:

- (void) doBackgroundColorAnimation {
static NSInteger i = 0;
NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor greenColor], [UIColor blueColor], [UIColor whiteColor], [UIColor blackColor], nil];

if(i >= [colors count]) {
    i = 0;
}

[UIView animateWithDuration:2.0f animations:^{
    self.view.backgroundColor = [colors objectAtIndex:i];           
} completion:^(BOOL finished) {


      ++i;
        [self doBackgroundColorAnimation];
    }]; 

}

However, my swift code isn't working? I print the word "done" in my completion method but for some reason it spams the console like its being called constantly?

What am I doing wrong?

import UIKit

class ViewController: UIViewController {

    override func prefersStatusBarHidden() -> Bool {
        return true
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tripOut()
    }

    func tripOut() {

        var i = 0

        let colors = [UIColor.redColor(),UIColor.blueColor(),UIColor.yellowColor()]

        if(i >= colors.count) {
            i = 0
        }

        UIView.animateWithDuration(2.0, animations: { () -> Void in

            self.view.backgroundColor = colors[i]

            }, completion: { (value: Bool) in
                ++i
                self.tripOut()
                println("done")
        })

        }

    }

Upvotes: 1

Views: 94

Answers (1)

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71854

It is not working because when tripOut called new instance colors and i created so make them global and here is your working code:

import UIKit

class ViewController: UIViewController {

    let colors = [UIColor.redColor(),UIColor.blueColor(),UIColor.yellowColor()]
    var i = 0

    override func prefersStatusBarHidden() -> Bool {
        return true
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tripOut()
    }

    func tripOut() {

        if(i >= colors.count) {
            i = 0
        }

        UIView.animateWithDuration(2.0, animations: { () -> Void in

            self.view.backgroundColor = self.colors[self.i]

            }, completion: { (value: Bool) in
                self.i++
                self.tripOut()
                println("done")
        })

    }

}

Upvotes: 1

Related Questions