如何在 Swift Assets.xcassets 中查找以字符串开头的特定图像

How to find specific images which start with a string in Swift Assets.xcassets

我正在开发一个 swift 应用程序,需要找到一些以特定字符串开头的图像,但我不知道如何从 Assets.xcassets.

中找到这些图像

我所有的图片都在 Assets.xcassets

谢谢

首先你应该在开头用标识符命名你想要的图像。我将使用星这个词作为示例。

图片名称应为 star1、star2、star3、star4 等。此代码应该有效。

var imagesCollected = [UIImage]()

for n in 1 ... 10{ //10 is whatever number you want
    let imageloaded = UIImage(named: "star\(n)")
    imagesCollected.append(imageloaded)
}

imagesCollected 应该有你所有的图片。让我知道是否有效。

尼尔

无法通过这种方式访问​​资产文件夹。一种方法是在您的计算机上创建一个包含所有图像的文件夹,然后拖到 Xcode 项目中。不要忘记 select "Create folder references for any added folders" 选项。使用该引用文件夹,您可以访问所有图像:

guard let _resourcePath = Bundle.main.resourcePath else{
        return
    }
    do{
        if let url = NSURL(string: _resourcePath)?.appendingPathComponent("YOUR FOLDER NAME"){
            let resourcesContent = try FileManager().contentsOfDirectory(at: url, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)

            for imageUrl in resourcesContent {
                let imageName = imageUrl.lastPathComponent
                print(imageName)
                //CHECK IMAGE NAME STRING
            }
        }
    }catch let error{
        print(error.localizedDescription)
    }

你自己知道图片的名字吗?我的意思是您是自己手动将图像加载到 Assets.xcassets 中还是以编程方式添加它们? 如果这样做,您可以创建一个字典,并在每次将图像添加到 Assetts.xcassets.

时在代码中手动或以编程方式添加图像名称。

imageDict = [category:[animalType]] 二维字典。 访问方式如下

import UIKit

var NaturePicsDict: [String : [String]] = ["cats":["Lion", "Tiger", "Panther"],
                                          "Birds": ["Hawk", "Parrot", "Sparrow", "Blackbird"]
                                          ]

//create an array of animal names for each category and then construct the full image file name from the category:animal using string concatination.

var animalsForCategory:[String] = []

for category in NaturePicsDict.keys {
    print("key = \(category) animal =" ,NaturePicsDict[category]!)
    let animals = NaturePicsDict[category]!
    for animalName in animals {
        let imageName: String = "\(category)_\(animalName)"
        print("imageName = \(imageName)")
    }
}

抱歉所有的编辑。我正在学习如何使用这个网站。无论如何,我的代码片段的输出是:

key = cats animal = ["Lion", "Tiger", "Panther"]
imageName = cats_Lion
imageName = cats_Tiger
imageName = cats_Panther
key = Birds animal = ["Hawk", "Parrot", "Sparrow", "Blackbird"]
imageName = Birds_Hawk
imageName = Birds_Parrot
imageName = Birds_Sparrow
imageName = Birds_Blackbird

希望这对您有所帮助。我刚刚在我正在编写的应用程序中使用了 3D 字典,发现它是一种非常紧凑的存储和访问向下钻取信息的方式。