我在我的应用程序中编写了一段代码,该代码应该生成1-10的随机数,我的图像全部命名为1-10。然后它应该在UIImageView中在屏幕上显示该图像。这是我的代码:
import UIKit
import Foundation
class ViewController: UIViewController {
@IBOutlet var QuoteImage: UIImageView!
func randomImagePicker() {
var QuoteImages: [UIImage] {
var QuoteImages: [UIImage] = []
// Create images named 1 - 10
let randomImageIndex = Int(arc4random_uniform(10) + 1)
// Assign the image property of the imageView to the element behind the random index in the images array
self.QuoteImage.image = QuoteImages[randomImageIndex]
let image = UIImage(named: "\(randomImageIndex)")!
QuoteImages.append(image)
// Create a random index
return QuoteImages
}
}
}
答案 0 :(得分:0)
我建议只需获取索引,然后相应地设置图像视图的image
属性:
class ViewController: UIViewController {
@IBOutlet var quoteImageView: UIImageView!
func randomImagePicker() {
let index = Int(arc4random_uniform(10) + 1)
quoteImageView.image = UIImage(named: "\(index)")!
}
}
如果您需要将阵列用于其他目的,请说明您的意图,我们可以澄清您如何实现这一目标。但是,如果您只是想将图像视图的image
设置为随机图像,则上述内容就足够了。