【问题标题】:getting an array of images to collection view将一组图像获取到集合视图
【发布时间】:2019-02-08 15:02:31
【问题描述】:

我正在尝试在我的文档目录中获取一组图像以显示在 UICollectionView 中我无法获取实际的图像数组。我花了一些时间尝试在谷歌上搜索,但大多数人似乎是从应用程序包中获取他们的图像。我需要我的图像来自文档。

这是我尝试使用的代码:

  func getImageArray() {
    let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
    let nsUserDomainMask    = FileManager.SearchPathDomainMask.userDomainMask
    let paths               = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
    if let dirPath          = paths.first
    {
        let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("Images")
        let image    = UIImage(contentsOfFile: imageURL.path)

        imageArray.append(image)
        print(imageURL)
    }

}

我对 swift 很陌生,所以答案可能很明显。有人可以指出我正确的方向或告诉我我做错了什么

【问题讨论】:

  • 您尝试从指向字典的 URL 创建 UIImage。
  • 好的,所以我需要一个指向我目录中每个图像的 URL 数组?对吗?

标签: arrays swift uicollectionview uiimage


【解决方案1】:

您可以尝试读取目录内容,然后单独循环以从 urls 创建图像

do {
    let allImages = URL(fileURLWithPath: dirPath).appendingPathComponent("Images") 
    let directoryContents = try FileManager.default.contentsOfDirectory(atPath: allImages.path) 
    for con in directoryContents { 
      let img = URL(fileURLWithPath:allImages).appendingPathComponent(con) 
      let image = UIImage(contentsOfFile: img.path) 
      imageArray.append(image)
   }
}
catch {
  print(error)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-08
    • 2017-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-20
    相关资源
    最近更新 更多