iOS Swift - 改变背景颜色

时间:2015-09-18 05:27:04

标签: ios objective-c swift animation colors

我试图通过不同的颜色使背景颜色循环。

我发现代码在objective-c中执行:

- (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];
    }]; 

}

然而,我的快速代码无效?我在完成方法中打印“完成”这个词,但由于某种原因,它会像控制它一样被调用控制台吗?

我做错了什么?

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

        }

    }

1 个答案:

答案 0 :(得分:1)

它无效,因为当tripOut调用了新实例colors并创建了i时,请将它们设为全局,这是您的工作代码:

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

    }

}
相关问题