如何从计数器更改 UIimage 视图中的图像

How to change image in UIimage view from counter

我真的很苦恼如何根据我创建的计数器/计时器每 2 分钟更改一次图像。我希望 UIImage 视图显示一个图像 2 分钟,然后根据我的柜台切换到另一个图像,然后是另一个图像,然后是另一个图像。这是计数器代码。

@objc func runTimer() {
    counter += 0.1
    // HH:MM:SS:
    let flooredCounter = Int(floor(counter))
    let hour = flooredCounter / 3600
    let minute = (flooredCounter % 3600) / 60
    var minuteString = "\(minute)"
    if minute < 10 {
        minuteString = "0\(minute)"
    }
    let second = (flooredCounter % 3600) % 60
    var secondString = "\(second)"
    if second < 10 {
        secondString = "0\(second)"
    }
    _ = String(format: "%.1f", counter).components(separatedBy: ".").last!

    timerLabel.text = "\(hour):\(minuteString):\(secondString)"

这是开始、暂停和重置按钮

@IBAction func startWorkingAction(_ sender: Any)
{
    if !isTimerRunning {
        timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(runTimer), userInfo: nil, repeats: true)

        isTimerRunning = true

        resetButton.isEnabled = false
        resetButton.alpha = 0.2

        pauseButton.isEnabled = true
        pauseButton.alpha = 1.0

        startWorkingButton.isEnabled = false
        startWorkingButton.alpha = 0.2

        AudioServicesPlaySystemSound(1519)
    }

}
@IBAction func pauseAction(_ sender: Any)
{
    resetButton.isEnabled = true
    resetButton.alpha = 1.0

    startWorkingButton.isEnabled = true
    startWorkingButton.alpha = 1.0

    pauseButton.isEnabled = false
    pauseButton.alpha = 0.2

    isTimerRunning = false
    timer.invalidate()

    AudioServicesPlaySystemSound(1520)
}
@IBAction func resetAction(_ sender: Any)
{
    timer.invalidate()
    isTimerRunning = false
    counter = 0.0

    timerLabel.text = "0:00:00"

    resetButton.isEnabled = false
    resetButton.alpha = 0.0

    pauseButton.isEnabled = false
    pauseButton.alpha = 0.0

    startWorkingButton.isEnabled = true
    startWorkingButton.alpha = 1.0

    AudioServicesPlaySystemSound(1520)

}

并且 uiimage 的出口是

  @IBOutlet weak var treeGrow: UIImageView!

如有任何帮助,我们将不胜感激。谢谢!

这个其实很容易解决。这就是我在我的应用程序中使用它的方式:

//MARK: ImagePreviewAnimation

// timer for imagePreview
    var timer: Timer?
    var currentImage: UIImage?
    var currentImageIndex = 0

    func startImagePreviewAnimation(){
        timer = Timer.scheduledTimer(timeInterval: 1.6, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
    }

    @objc func timerAction(){
        currentImageIndex = (currentImageIndex + 1) % Constants.ImageList.images.count
        UIView.transition(with: self.imagePreview, duration: 0.5, options: .transitionCrossDissolve, animations: {
            self.imagePreview.image = Constants.ImageList.images[self.currentImageIndex]
            self.currentImage = self.imagePreview.image
        })
    }

这会每 1.6 秒更改一次图像,并进行柔和过渡。要知道的一件重要事情是,如果你去另一个ViewController,你应该打电话给timer.invalidate()

Constants.ImageList 是我的简单列表,其中包含所有图像。通过调用 % 的技巧,列表总是在到达末尾时重新开始。