随机图像到(许多)图像视图 [英] Random images to (many) Image Views

查看:78
本文介绍了随机图像到(许多)图像视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可悲的是,我有36个UIImage,并且需要为每个图像设置一个随机图像.

Sadly, I've got 36 UIImages and need to set a random image to each one.

我的6张图片都已命名;

My 6 images are named;

"Owl1"
"Owl2"
"Owl3"
"Owl4"
"Owl5"
"Owl6"

因此,我想为我的36个不同的UIImage设置一个随机图像.做这个的最好方式是什么?数组?到目前为止,这是我的尝试".

So, I want to set one random image to my 36 different UIImages. What is the best way to do this? An array? Here's my "try" so far.

var images: [UIImage] = [
UIImage(named: "Owl1")!,
UIImage(named: "Owl2")!,
UIImage(named: "Owl3")!,
UIImage(named: "Owl4")!,
UIImage(named: "Owl5")!,
UIImage(named: "Owl6")!
]

var randomUIImage = [Image1, Image2, Image3, Image4, Image5...]
        randomUIImage.shuffleInPlace()

randomUIImage[0].image = images[0]
randomUIImage[1].image = images[1]

但是我意识到这是行不通的,并且我无法为所有36张图像制作此代码……有人有更好的主意吗? ;-)

But I realized this will not work, and I can't make this code for all 36 images... Anyone got a better idea? ;-)

推荐答案

提示:您可以使用range +映射来创建图像数组.

Tip: you can use a range + map to create an array of your images.

let images = (1...6).map { UIImage(named: "Owl\($0)") }

(1...6)生成一个从1到6(包括6)的Int集合,并使用map为每个Int创建一个新的UIImage实例,并使用它们进行命名-因为您已命名图像为了方便.就像做一个循环并将UIImage的新实例添加到循环内的数组一样,使用一个索引来命名:"Owl1","Owl2"等.

(1...6) produces a collection of Ints, from 1 to 6 (including 6), and with map we create a new instance of UIImage for each Int, using them for the naming - since you named your images in order, it's convenient. It's like doing a loop and appending a new intance of UIImage to an array inside the loop, using an index for the naming: "Owl1", "Owl2", etc.

如果您的数组中也有UIImageViews,则可以为图像分配一个循环.

If you also have your UIImageViews in an array, you can assign the images with a loop.

这是一个示例(我没有在Xcode上进行验证,但它应该接近您的需求):

Here's an example (I didn't verify on Xcode but it should be close to what you need):

for view in imageViewsArray { // the array with the 36 imageViews
    // a random index for the array of 6 images
    let randomIndex = Int(arc4random_uniform(UInt32(images.count))
    // assign the randomly chosen image to the image view
    view.image = images[randomIndex]
}

这篇关于随机图像到(许多)图像视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆