如何从计数器更改UIimage视图中的图像
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何从计数器更改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
秒更改图像并进行软过渡。要知道的重要一点是,如果转到另一个timer.invalidate()
,则应呼叫ViewController
。
Constants.ImageList
是我仅包含所有图像的列表。通过调用%
的技巧,列表总是在到达结尾时重新启动。
以上是关于如何从计数器更改UIimage视图中的图像的主要内容,如果未能解决你的问题,请参考以下文章