I'm fairly new to Swift and having some trouble iterating through a list of images to animate them. I have all of them named, for instance "aquarium-x", with x being a number from 1-29, depending on how many images I have for the specific animation. This is the code that I have for that part
我对Swift相当新,并且在遍历图像列表时遇到一些麻烦来制作动画。我将所有这些命名为“aquarium-x”,其中x是1-29的数字,具体取决于我对特定动画的图像数量。这是我对该部分的代码
func checkAnimationImages() -> [AnyObject] {
var i = 0
var catGifArray = [UIImage]()
var image = UIImage(named: "-\(i)")
while (image != nil){
catGifArray.append(image!)
++i
image = UIImage(named: "-\(i)")
}
return catGifArray.map {
return $0.CGImage as! AnyObject
}
}
My problem is I can't figure out how to also incorporate an array of strings into the UIImage so I don't need to type all the names out.
我的问题是我无法弄清楚如何将一个字符串数组合并到UIImage中,所以我不需要输出所有的名字。
var catGifName:[String] = [
"3d",
"piano1",
"aquarium",
"bag",
"bitey",
"black",
"blackcat"]
I tried to put the name of the array in the "-/(i)" portion but that gives back an error.
我试图将数组的名称放在“ - /(i)”部分,但这会给出错误。
0
I think what you probably need is to pass in your list of filenames, and add the images to the array in a similar manner you were starting. It'd be something like this:
我认为你可能需要的是传入你的文件名列表,并以与你开始时类似的方式将图像添加到数组中。它是这样的:
func checkAnimationImages(fileNames: [String]) -> [AnyObject] {
for name in fileNames {
var i = 0
var catGifArray = [UIImage]()
var image = UIImage(named: "\(name)-\(i)")
while (image != nil){
catGifArray.append(image!)
++i
image = UIImage(named: "\(name)-\(i)")
}
}
return catGifArray.map {
return $0.CGImage as! AnyObject
}
}
Of course the UIImage(named:...)
only works if the image is in the main bundle, but I assume that's how you've set yourself up.
当然,UIImage(名为:...)仅在图像位于主束中时才有效,但我认为这就是你如何设置自己。
Anyway, you'd call it like...
无论如何,你会把它称为......
self.checkAnimationImages(self.catGifNames)
1
It looks like what you need is a nested for loop:
看起来你需要的是一个嵌套的for循环:
var images = [UIImage]()
let catGifName = ["cat","piano","aquarium","bag"]
for name in catGifName {
for i in 1...29 {
if let image = UIImage(named:"\(name)-\(i)") {
images.append(image)
}
}
}
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2016/02/13/b69f9fa0fb0858e9dcba304c52914281.html。