Here is the code that I am using; my timer is at the bottom. I don't know how to change the color when the timer goes off.
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()
}
}
}
I need the button to turn the color red after my timer ends and if possible when the button is pressed have the color turn back to black.
CodePudding user response:
You could add an IBOutlet
to the button, and then use that outlet to update the button in your updateTimer
routine.
An alternative to adding an IBOutlet
to the button is to pass the button as the userInfo:
parameter of the Timer
.
You can pass anything you want as the userInfo:
and right now you're just passing nil
. If you change nil
to sender
, then the button will be passed along to the Timer
.
timer = Timer.scheduledTimer(timeInterval: 1.0, target:self,
selector: #selector(updateTimer), userInfo: sender,
repeats: true)
Then, add the Timer
parameter to updateTimer
:
@objc func updateTimer(t: Timer) {
if let button = t.userInfo as? UIButton {
button.backgroundColor = .red
}
}
Making use of userInfo
makes even better sense if you have multiple buttons that share the same updateTimer
code. By creating a structure to hold the secondsPassed
and button
and passing that structure as userInfo:
, you could have multiple buttons using multiple timers at the same time and each Timer
would know which button it was assigned to.