简体   繁体   English

如何在swift中将变量值放入另一个变量名中

[英]How to put variable value inside another variable name in swift

I am pretty new to Swift and I want to make a pretty big list of images called image1, image2, image3 and so on.我是 Swift 的新手,我想制作一个很大的图像列表,称为 image1、image2、image3 等等。 The problem is that I need to make something like this:问题是我需要做这样的事情:

var index = 1 ... image(index).image = ... index+=1 var index = 1 ... image(index).image = ... index+=1

where index is a counter for my images ( image(index) to be image1, for example) but I don't know the right syntax for image(index).其中 index 是我的图像的计数器(例如 image(index) 为 image1),但我不知道 image(index) 的正确语法。

Can someone let me know how?有人可以让我知道如何吗?

try this尝试这个

let imageArray = [UIImage]()

for i in 0..<limit {
    imageArray.append(UIImage(named: "image\(i)"))
}

If you want to init the image by name, image1jpg image2.jpg... image53.jpg you should do this:如果你想按名称初始化图像, image1jpg image2.jpg... image53.jpg 你应该这样做:

let imageName = "image\\(index).jpg"

Then just create the image with the name然后只需创建具有名称的图像

I guess you only need an array …我猜你只需要一个数组……

var images = [String]()
images.append("image1.jpg")
images.append("image2.jpg")
print(images.first) // "image1.jpg"
print(images[1]) // "image2.jpg"

Initially you need drag drop your all images into your Xcode project file with naming convention like image_1.png, image_2.png .... image_50.png最初,您需要使用命名约定将所有图像拖放到 Xcode 项目文件中,例如 image_1.png、image_2.png .... image_50.png

and write the code on your view controller

let imageArray:String = [String]()

for index in 1..<51 {
 imageArray.append(UIImage(named: "image_\(index)"))
 }

now you will get the an array of images name that reflect your stored images.

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

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