定时器用完后如何更换按钮的颜色



这是我正在使用的代码,代码底部是我的计时器,它是一个计时器,一旦达到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添加到按钮的替代方案是将该按钮作为TimeruserInfo:参数传递。

你可以传递任何你想要的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更有意义。通过创建一个结构来容纳secondsPassedbutton,并将该结构传递为userInfo:,您可以同时使用多个计时器来拥有多个按钮,每个Timer都会知道它被分配给了哪个按钮。

最新更新