如何在Swift中从文件夹中获取UIImage数组? [英] How to get array of UIImage, from folder, in Swift?

查看:1043
本文介绍了如何在Swift中从文件夹中获取UIImage数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的普通Xcode项目...

I have an ordinary Xcode project like this ...

注意有一个名为images的文件夹(它是一个实际的文件夹 - 而不仅仅是一个组)。它包含25个.png图像。

notice there's a folder (it is an actual folder - not just a group) named "images". It contains 25 ".png" images.

我想做的就是制作一个数组 UIimage 与每个图像。

All I want to do is make an array of UIimage with each of those images.

(或者甚至,图像名称或类似的数组,没关系 - 然后可以加载它们 UIImage(名称:

(Or even, an array of the image names or similar, that would be fine - then could load them UIImage(named:)

如何进入该文件夹images??子文件夹images / cars怎么样?

How do I get at that folder "images"?? What about a subfolder "images/cars"?

我尝试了类似的东西,但它什么都没找到......

I tried something like this but it finds nothing...

override func viewDidLoad()
    {
    let imageArray = NSBundle.mainBundle().URLsForResourcesWithExtension(
          "png", subdirectory: "images")
    print("test...")
    for n:NSURL in imageArray!
        { print("found ..." ,n) }
    }


推荐答案

我们假设图像在应用程序的资源包中。如果不是,您需要确保图像目录列在复制包资源中目标的构建阶段。

We we assume the images are in the app's resource bundle. If not you need to make sure that your images directory is listed in the "Copy Bundle Resources" in the "Build Phases" of the target.

编辑
这只是复制了将图像放入应用程序包中,如果您需要根据以下代码将文件夹复制到应用程序包中,请使用以下 StackOverflow问题以正确设置它。

这给出了我们可以使用UIImage(数据:)和NSData(contentsOfURL :)来使用URL,以便在需要时创建图像。

This gives us an array of URL's that we can then use with UIImage(data:) and NSData(contentsOfURL:) to create the image when needed.

获取包的资源路径和附加图像目录然后获取目录的内容。

Get the bundle's resource path and append the image directory then get the contents of the directory.

     if let path = NSBundle.mainBundle().resourcePath {

        let imagePath = path + "/images"
        let url = NSURL(fileURLWithPath: imagePath)
        let fileManager = NSFileManager.defaultManager()

        let properties = [NSURLLocalizedNameKey,
                          NSURLCreationDateKey, NSURLLocalizedTypeDescriptionKey]

        do {
            let imageURLs = try fileManager.contentsOfDirectoryAtURL(url, includingPropertiesForKeys: properties, options:NSDirectoryEnumerationOptions.SkipsHiddenFiles)

            print("image URLs: \(imageURLs)")
            // Create image from URL
            var myImage =  UIImage(data: NSData(contentsOfURL: imageURLs[0])!)

        } catch let error1 as NSError {
            print(error1.description)
        }
    }

这篇关于如何在Swift中从文件夹中获取UIImage数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆