gpt4 book ai didi

swift - 如何在 Swift 中设置按下按钮后的循环间隔?

转载 作者:行者123 更新时间:2023-11-30 11:23:57 25 4
gpt4 key购买 nike

我正在尝试为用户按下按钮后设置一个循环间隔计时器。例如,一旦按下“红色”交通信号灯,它将循环显示其余颜色(按顺序),每种颜色持续 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
}
}
}

最佳答案

奥特莱斯:-

@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
}
})
}

关于swift - 如何在 Swift 中设置按下按钮后的循环间隔?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50959889/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com