首页 > 解决方案 > 从包含图像的数组中自动随机更改图像视图图像 [swift]

问题描述

我正在尝试随机更改图像并将图像显示到图像视图,延迟几秒钟从包含图像的数组中。

但是当我按下按钮操作时,所有代码都能很好地执行我想要的,但我没有在模拟器中看到实时自动更改图像,只显示最后一个随机图像

这是我的代码

@IBOutlet weak var imageViewTop: UIImageView!

let myArray = [#imageLiteral(resourceName: "A"), #imageLiteral(resourceName: "B"), #imageLiteral(resourceName: "C"), #imageLiteral(resourceName: "D")]

@IBAction func buttonAction(_ sender: UIButton) {
        for i in 0..<myArray.count {
            print("Process start \(i)")
            
            imageViewTop.image = myArray.randomElement()
            
            print(myArray.randomElement()!)
            sleep(5)
            print("Process End \(i)")
        }
    }

这是我的控制台输出

我看到我的控制台输出打印语句延迟 5 秒,这工作正常。但看不到将我的图像视图中的图像一一更改为模拟器

进程开始 0

<UIImage:0x600000131050 命名(主:B){341, 341}>

进程结束 0

流程开始 1

<UIImage:0x600000131170 命名(主:C){341, 341}>

流程结束 1

进程启动 2

<UIImage:0x600000131050 命名(主:A){341, 341}>

流程结束 2

进程启动 3

<UIImage:0x600000131050 命名(主:C){341, 341}>

流程结束 3

Xcode 编辑器截图

标签: swiftxcode

解决方案


根据我的理解,您希望逻辑中的顺序图像更改。

您可以使用 Timer() 在特定时间间隔后更改图像。

在 Timer() 的帮助下检查下面的图像更改代码。

第1步:

//Create a Timer object.
var changeImageTimer: Timer?

第2步:

//Run your timer either from ViewDidLoad or on button click action.

@IBAction func buttonAction(_ sender: UIButton) {
    
    //Check timer running or not
    if let timer = changeImageTimer, timer.isValid {
        changeImageTimer?.invalidate()
    }
    
    //Change Image Randomly
//        changeImageTimer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(changeImageRandomly), userInfo: nil, repeats: true)
    
    //Change Image in sequence
    index = 0
    changeImageTimer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(changeImageInSequence), userInfo: nil, repeats: true)
}

第三步:

//Timer function where you can put your image change logic this method calls after a time interval.
@objc func changeImageRandomly() {
    //Rendom Pick from array
    print("Image changes randomly.")
    imageViewTop.image = myArray.randomElement()
}

@objc func changeImageInSequence() {
    print("Image Change in Sequence with Index = ",index)
    if index < myArray.count {
        //Seq Pick from array
        imageViewTop.image = myArray[index]
        index += 1
    } else {
        changeImageTimer?.invalidate()
    }
}

因此,在第 3 步,您有 2 个选项,您可以使用索引变量随机或按顺序更改图像,该变量将在每次调用时递增并更改图像。

检查此 GIF: https ://imgur.com/a/OvN1US2

希望这将帮助您在特定时间间隔获得图像更新。


推荐阅读