簡體   English   中英

iOS Swift-更改背景顏色

[英]iOS Swift - Changing background colours

我正在嘗試使背景色通過不同的顏色循環。

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

}

但是,我的快速代碼無法正常工作嗎? 我在完成方法中打印單詞“ done”(完成),但是由於某種原因它像經常被調用一樣向控制台發送垃圾郵件?

我究竟做錯了什么?

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稱為新實例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")
        })

    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM