我是这样做的。
首先,您可以通过以下方式创建一个 Bundle 来保存您的资产(例如图片)。
首先,创建一个新目标:
导航到 Xcode 主菜单,File => New => Target。然后选择“macOS选项卡”
从“框架和库”中选择“捆绑”。
给它你想要的名字,然后点击完成。您应该会在项目文件夹中看到该捆绑包。
二,Bundle构建设置的配置变化:
转到捆绑目标上的 Build Settings 并将 Base SDK 更改为 iOS。
第三,添加图片:
直接将您的图像添加到 Bundle,无需添加资产文件夹。只需拖放即可。
第四,构建捆绑包:
选择您的捆绑包作为目标,然后选择通用 iOS 设备并点击 Command + B
第五,.bundle 将出现在您的项目文件夹下的产品文件夹中。右键单击它并在 Finder 中查看它,然后将其拖放到主项目文件夹中。
最后,下面是我访问捆绑包中资产的方法。
// Empty UIImage array to store the images in it.
var images = [UIImage]()
let fileManager = FileManager.default
let bundleURL = Bundle.main.bundleURL
let assetURL = bundleURL.appendingPathComponent("MyBundle.bundle") // Bundle URL
do {
let contents = try fileManager.contentsOfDirectory(at: assetURL,
includingPropertiesForKeys: [URLResourceKey.nameKey, URLResourceKey.isDirectoryKey],
options: .skipsHiddenFiles)
for item in contents { // item is the URL of everything in MyBundle imgs or otherwise.
let image = UIImage(contentsOfFile: item.path) // Initializing an image
images.append(image!) // Adding the image to the icons array
}
}
catch let error as NSError {
print(error)
}
您的包中将包含 .plist 文件,因此,我建议您通过一个简单的条件来处理此问题,以检查文件名是否为 Info.plist,不要从中创建图像。
这是我以非常简单的方式处理它的方法。
let fileManager = FileManager.default
let bundleURL = Bundle.main.bundleURL
let assetURL = bundleURL.appendingPathComponent("Glyphs.bundle")
do {
let contents = try fileManager.contentsOfDirectory(at: assetURL, includingPropertiesForKeys: [URLResourceKey.nameKey, URLResourceKey.isDirectoryKey], options: .skipsHiddenFiles)
for item in contents {
let imageName = item.lastPathComponent
if imageName != "Info.plist" {
let image = UIImage(contentsOfFile: item.path)
icons.append(image!)
}
}
}
catch {
//print(error)
showAlert(withTitle: "Error", message: "Can't get the icons.")
}