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



我真的很纠结如何根据我创建的计数器/计时器每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是我的简单列表,它包含所有图像。使用调用%的技巧,列表总是在到达末尾时重新启动。

最新更新