我需要一张图片出现在框架中。我发现需要知道它所在应用程序的名称的唯一方法。是否有其他方法可以将资产放入您的框架中? (要发布此信息:
大约 5 年前我发布了这个答案。它包含两段代码,用于从框架的捆绑包中提取资产。关键代码是这样的:
public func returnFile(_ resource:String, _ fileName:String, _ fileType:String) -> String {
let identifier = "com.companyname.appname" // replace with framework bundle identifier
let fileBundle = Bundle.init(identifier: identifier)
let filePath = (fileBundle?.path(forResource: resource, ofType: "bundle"))! + "/" + fileName + "." + fileType
do {
return try String(contentsOfFile: filePath)
}
catch let error as NSError {
return error.description
}
那么,如果您的框架需要知道两件事(应用程序包和明暗模式),那么如果您的框架调整了这段代码会怎么样?将
identifier
移出以供应用程序访问,而不是此函数的本地访问。然后创建一个新变量(我认为这是最好的方法)或一个新函数来根据浅色或深色模式使用正确的资产集。
现在您的应用程序可以
import
您的框架,并在其使用者中进行适当的设置。 (我没有尝试过,但理论上我认为它应该有效。)
创建一个文件夹“资源”。将图像拖放到此文件夹中
在单独的 .swift 文件中创建一个类“ImageLoader”。
import Foundation
import UIKit
public class ImageLoader {
// Function to load an image from the framework bundle
public static func loadImage() -> UIImage {
// Get the bundle where the ImageLoader class resides
let frameworkBundle = Bundle(for: ImageLoader.self)
// Print the bundle for debugging purposes
// Try to retrieve the URL of the image resource named "image.png" from the bundle
guard let imageUrl = frameworkBundle.url(forResource: "image", withExtension: "png"),
// Try to load the image data from the retrieved URL
let imageData = try? Data(contentsOf: imageUrl),
// Try to create a UIImage from the loaded image data
let image = UIImage(data: imageData) else {
// If any of the above steps fail, use a default system image "chevron.right"
let img = UIImage(systemName: "chevron.right")!
return img
}
// Return the loaded image
return image
}
}
确保 Resources 文件夹和 ImageLoader.swift 文件应位于同一包内。
使用以下代码调用视图文件中的图像
VStack {
Text("Image imported")
Image(uiImage: ImageLoader.loadImage())
.resizable()
}