是否可以使用特定前缀计算资产目录中的图片?

时间:2016-04-02 19:49:38

标签: ios swift uiimage alassetslibrary

是否可以在资产目录中计算具有特定前缀的图片? 例如,我有像这样的图像:

Cocktail_01

Cocktail_02

...

Cocktail_nn

和其他类似的团体。

当我的应用程序启动时,我会执行如下代码:

var rec_cocktail = [UIImage]()
    for i in 1..<32 {
        if i < 10 {
            let name: String = "Cocktail__0" + i.description
            rec_cocktail.append(UIImage(named: name)!)
        } else {
            let name: String = "Cocktail__" + i.description
            rec_cocktail.append(UIImage(named: name)!)
        }
    }
    alcoholImages.append(rec_cocktail)

这是完美的,但我加载了很少的组,每个组都有不同数量的图像。每次添加或删除资产目录中的图片时,我都必须检查并更改范围。

1 个答案:

答案 0 :(得分:2)

使用文件夹而不是Images.xcassets可能更容易。在计算机上创建您喜欢的层次结构并将其拖到Xcode项目中。请务必选择:

  

为任何添加的文件夹创建文件夹引用

然后,因为您在构建应用程序时现在有文件夹引用,所以可以使用循环遍历这些文件夹中的项目。

例如,我拖入一个名为“Cocktail”的文件夹并创建了引用。现在我可以使用:

遍历此文件夹中的项目
let resourcePath = NSURL(string: NSBundle.mainBundle().resourcePath!)?.URLByAppendingPathComponent("Cocktail")
let resourcesContent = try! NSFileManager().contentsOfDirectoryAtURL(resourcePath!, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles)

for url in resourcesContent {
    print(url)
    print(url.lastPathComponent)
    print(url.pathExtension!) // Optional

}

url.lastPathComponent是图像的文件名(例如Cocktail_01.jpeg),url本身是图像的完整路径。

如果你维护一个文件夹结构,很容易迭代它们,如果你想要在同一个文件夹中的所有图像,你可以创建一个只有你需要的图像名称的数组,并使用以下方法迭代:

// The Array of Image names
var cocktailImagesArray : [String] = []

// Add images to the array in the 'for url in resourceContent' loop
if (url.lastPathComponent?.containsString("Cocktail")) {
    self.cocktailImagesArray.append(url.lastPathComponent)
}

通过这种方式,您可以获得包含Cocktail的所有图像,并将它们添加到您的阵列中。现在,您可以使用以下方法简单地迭代新创建的数组:

for imageName in self.cocktailImagesArray {
    // Do something
}
相关问题