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

Is it possible to count pictures in asset catalog with particular prefix?

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

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)

效果很好,但我要加载的组很少,而且每个组的图片数量都不一样。每次从资产目录中添加或删除图片时,我都必须检查和更改范围。

使用文件夹可能比 Images.xcassets 更容易。在您的计算机上创建您喜欢的层次结构并将其拖到您的 Xcode 项目中。确保你 select:

Create folder references for any added folders

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

例如,我拖入了一个名为 "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
}