如果声明不适用于计时器

时间:2018-05-20 03:58:23

标签: ios if-statement timer swift4

10秒击中计时器。我希望改变背景颜色。现在我的代码无效。当代码达到10秒时,没有任何改变。我也不认为计时器工作正常。

@IBOutlet var espn: UILabel!

var TIMER = Timer()
var seconds = 0


override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)




    if seconds == 10{self.view.backgroundColor = UIColor.red
    }

}
@IBAction func startTimer() {       

        TIMER = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(threeVC.clocker), userInfo: nil, repeats: true)


}


@objc func clocker() {
    seconds += 1
    espn.text = String( seconds)   
    }
}

1 个答案:

答案 0 :(得分:0)

试试这段代码:

@IBOutlet var espn: UILabel!

var TIMER = Timer()
var seconds = 0


override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)        
}

@IBAction func startTimer() {

    TIMER = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(threeVC.clocker), userInfo: nil, repeats: true)


}


@objc func clocker() {
    seconds += 1
    espn.text = String( seconds)
    if seconds == 10{
        self.view.backgroundColor = UIColor.red
        print("soda")
    }
}

if语句应写在@objc func clocker()而非viewDidAppear