2016-09-18 51 views

回答

0

你可能知道,你不訪問使用字符串字面路徑的項目文件夾中的文件。而是使用NSBundle提供的功能。令人高興的是,這些功能可以滿足您的需求。看着在爲一個NSBundle的開發者參考:

https://developer.apple.com/library/content/documentation/CoreFoundation/Conceptual/CFBundles/AccessingaBundlesContents/AccessingaBundlesContents.html

我想你想從這個文件是3-11的上市,其中介紹瞭如何拉一個給定類型的所有資產,從包:

CFArrayRef birdURLs; 

// Find all of the JPEG images in a given directory. 
birdURLs = CFBundleCopyResourceURLsOfType(mainBundle, 
       CFSTR("jpg"), 
       CFSTR("BirdImages")); 

希望有幫助!

+0

從概念上講,我明白了,但我如何在Swift中做到這一點?我試着調整代碼以在我的項目中工作,並且吐出了很多有趣的錯誤。 –

0

您無法在運行時以編程方式訪問.xcassets文件。我也在處理類似的任務,我提出的解決方案非常簡單。圖像使用以下約定命名:imageNameAndIdentifier(例如:heart0,heart1,heart2等)。使用構建圖像全名並創建UIImage的循環,我可以獲得所有需要的圖像。

let stickerName = "heart" 
    var images = [UIImage]() 
    var lastImageIndex = 0 

    lastImageIndex = lastStickerImageIndex(name: stickerName) 

    for index in 0...lastImageIndex { 
     images.append(UIImage.init(named: stickerName + "\(index)")) 
    } 

請注意lastImageIndex變量。它的值是根據文件中包含給定字符串的文件數和減去一個單位來計算的,因爲最後一個索引是=(length_of_array - 1)。

private func lastStickerImageIndex(name: String) -> Int { 
    return (FileManager.default.numberOfFilesWhichNameContains(string: name) - 1) 
} 

我創建了一個擴展,它根據應該包含在所需文件名中的字符串返回文件數。

extension FileManager { 

    func numberOfFilesWhichNameContains(string: String) -> Int { 

     do { 
      let bundleFiles = try self.contentsOfDirectory(atPath: Bundle.main.bundlePath) 
      let filteredBundleFiles = bundleFiles.filter({ 
       $0.contains(string) 
      }) 

      return filteredBundleFiles.count 

     } catch let error { 
      print(error) 
     } 

     return 0 
    } 

} 
+0

謝謝!我會給它一個去讓你知道發生了什麼。乾杯 –

+0

嘿,那裏,試着你的代碼,並得到「使用未解析的標識符名稱」。是否應該通過函數傳遞? –

+0

這是公開回購還是要點?謝謝! –