我正在尝试为用户按下的按钮设置一个循环间隔计时器。例如,一旦按下“红色”交通信号灯,它将在剩余的颜色中(依次)循环显示每种颜色5秒钟。
import UIKit
class ViewController: UIViewController {
var timer : Timer?
func redButton() {
timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: Selector(("redButton")), userInfo: nil, repeats: true)
}
func redButton() {
}
var lightRed = true;
var lightYellow = true;
var lightGreen = true;
@IBOutlet weak var stopLabel: UILabel!
@IBAction func redButton(_ sender: Any) {
//TODO: Show text information when 'stop' button is clicked
stopLabel.text = "Red means stop! Do not proceed forward."
lightRed = !lightRed
if lightRed {
view.backgroundColor = .white
} else {
view.backgroundColor = .red
}
}
@IBOutlet weak var waitLabel: UILabel!
@IBAction func yellowButton(_ sender: Any) {
//TODO: Show text information when 'slow' button is clicked
waitLabel.text = "Yellow means wait, or slow down, as it is about to turn red!"
lightYellow = !lightYellow
if lightYellow {
view.backgroundColor = .white
} else {
view.backgroundColor = .yellow
}
}
@IBOutlet weak var goLabel: UILabel!
@IBAction func greenButton(_ sender: Any) {
//TODO: Show text information when 'go' button is clicked
goLabel.text = "Green means go! Now is the time to proceed forward"
lightGreen = !lightGreen
if lightGreen {
view.backgroundColor = .white
} else {
view.backgroundColor = .green
}
}
}
答案 0 :(得分:0)
Outles:-
@IBOutlet weak var viewGreen: UIView!
@IBOutlet weak var viewYellow: UIView!
@IBOutlet weak var viewRed: UIView!
@IBOutlet weak var btnStart: UIButton!
var timer : Timer?
var isRed = true
var isYellow = false
var isGreen = false
开始按钮操作:-
@IBAction func btnStart(_ sender: UIButton) {
self.viewRed.backgroundColor = .red
self.viewYellow.backgroundColor = .white
self.viewGreen.backgroundColor = .white
self.isRed = false
self.isYellow = true
self.isGreen = false
timer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true, block: { (timer) in
if self.isRed {
self.viewRed.backgroundColor = .red
self.viewYellow.backgroundColor = .white
self.viewGreen.backgroundColor = .white
self.isRed = false
self.isYellow = true
self.isGreen = false
} else if self.isYellow {
self.viewRed.backgroundColor = .white
self.viewYellow.backgroundColor = .yellow
self.viewGreen.backgroundColor = .white
self.isRed = false
self.isYellow = false
self.isGreen = true
} else if self.isGreen {
self.viewRed.backgroundColor = .white
self.viewYellow.backgroundColor = .white
self.viewGreen.backgroundColor = .green
self.isRed = true
self.isYellow = false
self.isGreen = false
}
})
}