【问题标题】:iOS Swift - Changing background coloursiOS Swift - 更改背景颜色
【发布时间】:2015-09-18 05:27:03
【问题描述】:

我正在尝试通过不同的颜色使背景颜色循环。

我在这里找到了在 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];
    }]; 

}

但是,我的 swift 代码不起作用?我在我的完成方法中打印了“完成”这个词,但由于某种原因,它会像不断地调用它一样向控制台发送垃圾邮件?

我做错了什么?

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

        }

    }

【问题讨论】:

  • 因为tripOut 调用自己。永远。
  • 有没有办法让它调用一次?
  • 您可以使用一个标志并为该标志设置一个条件,它会在您需要时停止动画。

标签: ios objective-c swift animation colors


【解决方案1】:

它不起作用,因为当 tripOut 调用新实例 colorsi 创建时,请将它们设为全局,这是您的工作代码:

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

    }

}

【讨论】:

    猜你喜欢
    • 2018-10-25
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-16
    • 1970-01-01
    • 2015-10-09
    • 2013-08-08
    相关资源
    最近更新 更多