How to get Assets.xcassets file names in an Array (or some data structure?)

时间:2016-07-11 22:53:56

标签: ios swift

I'm trying to use Swift to iterate over the images I have put into my Assets folder. I'd like to iterate over them and insert them into a .nib file later, but so far I cannot find how to get something like:

let assetArray = ["image1.gif", "image2.gif", ...]

Is this possible? I've been playing with NSBundle.mainBundle() but couldn't find anything on this. Please let me know. Thanks!

1 个答案:

答案 0 :(得分:11)

Assets.xcassets不是文件夹,而是包含使用Assets.car作为其文件名的所有图像的存档。

如果你真的想阅读资产文件,那么你需要使用一些可以提取文件内容的库,如one

或者您可以在项目中创建一个包并拖动您在那里的所有图像。就我而言,我的项目中有Images.bundle。要获取文件名,您可以执行以下操作:

let fileManager = NSFileManager.defaultManager()
let bundleURL = NSBundle.mainBundle().bundleURL
let assetURL = bundleURL.URLByAppendingPathComponent("Images.bundle")
let contents = try! fileManager.contentsOfDirectoryAtURL(assetURL, includingPropertiesForKeys: [NSURLNameKey, NSURLIsDirectoryKey], options: .SkipsHiddenFiles)

for item in contents
{
  print(item.lastPathComponent)
}

SWIFT 3版本:

let fileManager = FileManager.default
let bundleURL = Bundle.main.bundleURL
let assetURL = bundleURL.appendingPathComponent("Images.bundle")
let contents = try! fileManager.contentsOfDirectory(at: assetURL, includingPropertiesForKeys: [URLResourceKey.nameKey, URLResourceKey.isDirectoryKey], options: .skipsHiddenFiles)

for item in contents
{
    print(item.lastPathComponent)
}