【问题标题】:Function that returns an array of the string filenames of a directory in xcassets返回 xcassets 中目录的字符串文件名数组的函数
【发布时间】:2015-09-23 04:56:10
【问题描述】:

几个小时以来,我浏览了许多 Swift 和 Objective-C 帖子,以帮助我创建一个函数,该函数返回 xcassets 中目录的字符串文件名数组。然后我可以使用文件名数组创建另一个函数,向我的用户显示随机图像。

var imageDirectory  = [String]()


func getContentOfImageDirectory() -> [String] {

    imageDirectory.removeAll(keepCapacity: false)


    let fm = NSFileManager.defaultManager()

    let sourcePath = NSBundle.mainBundle().resourcePath!.stringByAppendingPathComponent("DeviceImagesFolder")

    var tempArray = fm.contentsOfDirectoryAtPath(sourcePath, error: nil)


    if tempArray != nil {

        self.imageDirectory = tempArray as! [String]

        return imageDirectory

    }

    else {
        println("tempArray was nil")


        if fm.fileExistsAtPath(sourcePath){

            println("There is a file")
            return []
        }

        else {
            println("There is not a file")
            return []
        }
    }

}

但是 tempArray 不断返回 nil 和“​​没有文件”。显然,我的函数返回“DeviceImagesFolder”的整个包含,而不是文件名数组。

如果有人能提供解决此问题的方法,将不胜感激。 干杯。

【问题讨论】:

  • stackoverflow.com/questions/19346394/…。尝试保存一个图像名称数组并从数组中随机获取图像名称。
  • 但是如何在不手动将每个图像的文件名输入到数组中的情况下获得图像名称数组?

标签: ios swift path uiimage xcasset


【解决方案1】:

Xcode 将 xcassets 文件夹中的文件编译成一个文件(名为“Assets.car”)。

因此,您应该只将文件添加到“普通”文件夹中,而不是使用 xcassets。确保在“复制捆绑资源”构建阶段复制它们。

【讨论】:

  • 首先,感谢您的回复。我已经按照您的建议完成了,当我添加图像的“普通”文件夹时,xcode 会自动将文件夹中的图像添加到“复制捆绑资源”本身(但不是实际文件夹本身)中,然后我运行代码,我仍然得到“tempArray 为零”和“没有文件”。您还有其他建议吗?
  • 当您将文件夹添加到 Xcode 时,请确保将其添加为“文件夹引用”,而不是作为组。然后该文件夹应在项目导航器中显示为蓝色。它也应该在“复制捆绑资源”步骤中显示为文件夹。
猜你喜欢
  • 2017-11-22
  • 2013-01-10
  • 1970-01-01
  • 2013-11-22
  • 1970-01-01
  • 2010-12-24
  • 2011-11-23
  • 2013-10-01
  • 1970-01-01
相关资源
最近更新 更多