试图每隔x秒更改一次backgroundColor

时间:2016-02-06 14:15:34

标签: ios swift nstimer uicolor

我想要做的是每隔5秒将我的屏幕的backgroundColor更改为新颜色,但我不断收到两个错误。一个是UIColor的扩展,它表示"声明仅在文件范围内有效"并在self.view.backgroundColor中,它表示"键入' UIColor'没有' randomColor'"的成员。谢谢你或你的帮助和时间,我打开它帮助其他人。以下是我的代码:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var person: UIView!

    extension UIColor {
        func randomColor() -> UIColor{
            let red = CGFloat(drand48())
            let green = CGFloat(drand48())
            let blue = CGFloat(drand48())
            return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
        }
    }
    func changeBackround() -> UIColor {
        self.view.backgroundColor = UIColor.randomColor()
    }

    override func viewDidLoad() {
        self.viewDidLoad()

        NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: Selector("changeBackground"), userInfo: nil, repeats: true)

    }

}

1 个答案:

答案 0 :(得分:1)

您不能在另一个类的声明范围内声明类扩展。你应该移动块

extension UIColor {
    func randomColor() -> UIColor {
        let red = CGFloat(drand48())
        let green = CGFloat(drand48())
        let blue = CGFloat(drand48())
        return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
    }
}

超出class ViewController: UIViewController

的范围

另外,这里func randomColor() -> UIColorUIColor的实例上声明了一个方法。您希望将此func声明为static以具有类方法。生成的文件应为

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var person: UIView!

    func changeBackround() -> UIColor {
        self.view.backgroundColor = UIColor.randomColor()
    }

    override func viewDidLoad() {
        self.viewDidLoad()

        NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: Selector("changeBackground"), userInfo: nil, repeats: true)

    }

}

extension UIColor {
    static func randomColor() -> UIColor {
        let red = CGFloat(drand48())
        let green = CGFloat(drand48())
        let blue = CGFloat(drand48())
        return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
    }
}