这是我正在使用的代码,代码底部是我的计时器,它是一个计时器,一旦达到60分钟,我希望按钮变成红色。
import UIKit
import AVFoundation
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func btnPressed1(_ sender: UIButton) {
sender.backgroundColor = sender.backgroundColor == UIColor.red ? UIColor.black : UIColor.red
}
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var progressBar1: UIProgressView!
let start = 5
var timer = Timer()
var player: AVAudioPlayer!
var totalTime = 0
var secondsPassed = 0
@IBAction func startButtonPressed(_ sender: UIButton) {
let startB = sender.titleLabel?.text
totalTime = start
progressBar1.progress = 0.0
secondsPassed = 0
titleLabel.text = "coffee timer"
timer = Timer.scheduledTimer(timeInterval: 1.0, target:self, selector: #selector(updateTimer), userInfo:nil, repeats: true)
}
@objc func updateTimer() {
if secondsPassed < totalTime {
secondsPassed += 1
progressBar1.progress = Float(secondsPassed) / Float(totalTime)
print(Float(secondsPassed) / Float(totalTime))
} else {
timer.invalidate()
titleLabel.text = "check coffee"
let url = Bundle.main.url(forResource: "alarm_sound", withExtension: "mp3")
player = try! AVAudioPlayer(contentsOf: url!)
player.play()
}
}
}
我需要按钮在计时器结束后将颜色变为红色,如果可能的话,当按下按钮时将颜色变回黑色。
您可以向按钮添加一个IBOutlet
,然后使用该出口更新updateTimer
例程中的按钮。
将IBOutlet
添加到按钮的替代方案是将该按钮作为Timer
的userInfo:
参数传递。
你可以传递任何你想要的userInfo:
,现在你只传递nil
。如果将nil
更改为sender
,则该按钮将传递给Timer
。
timer = Timer.scheduledTimer(timeInterval: 1.0, target:self,
selector: #selector(updateTimer), userInfo: sender,
repeats: true)
然后,将Timer
参数添加到updateTimer
:
@objc func updateTimer(t: Timer) {
if let button = t.userInfo as? UIButton {
button.backgroundColor = .red
}
}
如果您有多个按钮共享相同的updateTimer
代码,那么使用userInfo
更有意义。通过创建一个结构来容纳secondsPassed
和button
,并将该结构传递为userInfo:
,您可以同时使用多个计时器来拥有多个按钮,每个Timer
都会知道它被分配给了哪个按钮。