Swift功能未运行

时间:2019-06-05 09:22:38

标签: swift

我正在编写代码,在等待几秒钟后将覆盖层的alpha更改为1(因此可见),其中wait是0到10之间的随机数

import UIKit

class ViewController: UIViewController {

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

    @IBOutlet var Background: UIView!
    @IBOutlet weak var RedOverlay: UIView! //Currently  set to 0

    func BackgroundChange() {
        let wait = Int.random(in: 0 ... 10)
        DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(wait), execute: {
            self.RedOverlay.alpha = 1
        })
    }
}

一旦我运行程序,背景就不会变色,我是否需要运行函数或其他东西?

2 个答案:

答案 0 :(得分:1)

您必须在声明后调用BackgroundChange()函数。函数名称也应该以小写字母开头。这样做是个好习惯。

import UIKit

class ViewController: UIViewController {

    @IBOutlet var Background: UIView!
    @IBOutlet weak var RedOverlay: UIView! //Currently  set to 0

    override func viewDidLoad() {
        super.viewDidLoad()
        backgroundChange()
    }

    func backgroundChange() {
        let wait = Int.random(in: 0 ... 10)
        DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(wait), execute: {
            self.RedOverlay.alpha = 1
        })
    }
}

答案 1 :(得分:0)

您似乎在调用该方法。

请务必这样做,例如在viewDidAppear中:

import UIKit

class ViewController: UIViewController {

    override func viewDidAppear(_ animated: Bool) {
        changeBackground()
    }

    @IBOutlet var background: UIView!
    @IBOutlet weak var redOverlay: UIView! //Currently  set to 0

    func changeBackground() {
        let wait = Int.random(in: 0 ... 10)
        DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(wait)) {
            self.redOverlay.alpha = 1
        }
    }
}

请注意,以小写字母开头的方法,函数和属性名称是惯用的。