我试图在屏幕上显示一个随机图片,但我是Swift的新手,我不知道该怎么做。当应用程序打开时,我想要在图像视图中随机显示三张图像。 我该怎么做?
答案 0 :(得分:6)
生成0到2之间的随机数,并按随机生成的数字显示图像。
var random = arc4random_uniform(3) //returns 0 to 2 randomly
switch random {
case 0:
//show first image
case 1:
//show second image
default:
//show third image
}
答案 1 :(得分:2)
如果图像的名称基本相同。例如," Image1.png,Image2.png和Image3.png,那么你可以使用这段代码:
override func viewDidLoad() {
super.viewDidLoad()
ImageView.image = UIImage(named: "Image\(arc4random_uniform(3) + 1).png")
}
答案 2 :(得分:0)
imageArr = ["1.jpeg","2.jpeg","3.jpeg","4.jpeg"]
let RandomNumber = Int(arc4random_uniform(UInt32(self.imageArr.count)))
//imageArr is array of images
let image = UIImage.init(named: "\(imageArr[RandomNumber])")
let imageView = UIImageView.init(image: image)
答案 3 :(得分:0)
它对我有用( Swift 4.2 ):
let images: [UIImage] = [ #imageLiteral(resourceName: "randomImage1"),
#imageLiteral(resourceName: "randomImage2"),
#imageLiteral(resourceName: "randomImage3")]
let randomImage = images.shuffled().randomElement()