简体   繁体   English

如何快速从文件夹中获取随机图像?

[英]How to get a random image from a folder in swift?

So far I have created a folder of images and I am able to assign 1 of the images to a UIImageView . 到目前为止,我已经创建了一个图像文件夹,并且能够将其中一张图像分配给UIImageView

But what I want to do now is create a random generator, that will pick a random image from the folder, so if I was to create a button, I could display all of the images separately and randomly on a single UIImageView . 但是我现在要做的是创建一个随机生成器,它将从文件夹中选择一个随机图像,因此,如果我要创建一个按钮,则可以在一个UIImageView上单独显示所有图像。

However, this folder is going to have more than 100 images, so I don't want to hard code each one into an array. 但是,此文件夹将有100多个图像,因此我不想将每个图像硬编码为一个数组。 Also, the names of the image has to be unique to the image itself. 同样,图像名称必须是图像本身唯一的。

I have been searching online but cannot find information on how to code what will suit my needs. 我一直在网上搜索,但是找不到有关如何编码适合我需求的信息。 So how would I get and display a random image(s) from a folder in swift? 那么如何快速从文件夹中获取并显示随机图像呢?

You can name your images like this 您可以这样命名图像

image_0
image_1
image_2

Then use this code to populate your UIImageView 然后使用此代码填充您的UIImageView

let numberOfImages: UInt32 = 100
let random = arc4random_uniform(numberOfImages)
let imageName = "image_\(random)"
imageView.image = UIImage(named: imageName)

Update 更新

Since you don't want to rename your images you can create a plist file (type Array) where you put all the names of your images 由于您不想重命名图像,因此可以创建一个plist文件(类型为Array),在其中放置所有图像名称

在此处输入图片说明

And finally 最后

func loadRandomImage() {
    let path = NSBundle.mainBundle().pathForResource("Images", ofType: "plist")!
    let names = NSArray(contentsOfFile: path) as! [String]
    let random = Int(arc4random_uniform(UInt32(names.count)))
    let imageName = names[random]
    imageView.image = UIImage(named: imageName)
}

You either need to create an array of string filenames and pick a random filename from the array, or you need to use the file manager ( NSFileManager ) to get a list of the files in your folder and then pick from THAT array. 您需要创建一个字符串文件名数组并从该数组中选择一个随机文件名,或者您需要使用文件管理器( NSFileManager )获取文件夹中文件的列表,然后从THAT数组中进行选择。 Nether is very difficult. 虚空非常困难。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM