How to get array of UIImage, from folder, in Swift?

前端 未结 5 1438
别跟我提以往
别跟我提以往 2021-02-13 19:18

I have an ordinary Xcode project like this ...

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

5条回答
  •  面向向阳花
    2021-02-13 19:53

    You can follow these steps to download them:

    1. Create a new folder in finder and add all images (or folder, ... everything).

    2. Change folder name + ".bundle" (for example: YourListImage -> YourListImage.bundle).

    3. Add folder to project.

    4. Add FileManager extension:

      extension FileManager {
          func getListFileNameInBundle(bundlePath: String) -> [String] {
      
              let fileManager = FileManager.default
              let bundleURL = Bundle.main.bundleURL
              let assetURL = bundleURL.appendingPathComponent(bundlePath)
              do {
                  let contents = try fileManager.contentsOfDirectory(at: assetURL, includingPropertiesForKeys: [URLResourceKey.nameKey, URLResourceKey.isDirectoryKey], options: .skipsHiddenFiles)
                  return contents.map{$0.lastPathComponent}
              }
              catch {
                  return []
              }
          }
      
          func getImageInBundle(bundlePath: String) -> UIImage? {
              let bundleURL = Bundle.main.bundleURL
              let assetURL = bundleURL.appendingPathComponent(bundlePath)
              return UIImage.init(contentsOfFile: assetURL.relativePath)
          }
      }
      
    5. Use:

       let fm = FileManager.default
       let listImageName = fm.getListFileNameInBundle(bundlePath: "YourListImage.bundle")
       for imgName in listImageName {
           let image = fm.getImageInBundle(bundlePath: "YourListImage.bundle/\(imgName)")
       }
      

提交回复
热议问题