我创建了一个iOS应用,并向其中添加了一个框架。生成的框架没有类似于generate Single View App
的资源文件夹。因此,我在框架文件夹中创建了一个Assets文件夹,并将其拖放到xcode,选择目标作为我的框架。
我尝试使用资产,但资产未显示。可以告诉我如何正确执行此操作吗?是否可以在框架内创建资产文件夹?
我对iOS还是很陌生,因此不胜感激。预先感谢。
通常通过New File ...> Resources将[[Asset catalog添加到框架目标,但是要从此类资产中获取资源,它需要显式指定包,如下面的示例...
假设ImageProvider
位于框架目标中,则代码可以为public class ImageProvider {
// convenient for specific image
public static func picture() -> UIImage {
return UIImage(named: "picture", in: Bundle(for: self), with: nil) ?? UIImage()
}
// for any image located in bundle where this class has built
public static func image(named: String) -> UIImage? {
return UIImage(named: named, in: Bundle(for: self), with: nil)
}
}
当然您可以通过任何方式为此类命名。
首先,这是创建捆绑包以保存图像之类资产的方法。
First
,创建一个新目标:导航到Xcode主菜单,File => New => Target。选择“ macOS选项卡”,然后从“框架和库”中选择“捆绑包”。给您所需的名称,然后单击完成。您应该在项目文件夹中看到该捆绑包。
Second
,Bundle的构建设置中的配置更改:转到捆绑目标上的“构建设置”,然后将基本SDK更改为iOS。第三
,添加图像:将图像直接添加到捆绑包中,无需添加资源文件夹。只需拖放即可。第四
,构建捆绑包:选择捆绑包作为目的地,然后选择通用的iOS设备,然后按Command + BFifth
,. 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.") }
func filePathInFrameworkBundle(name: String)->String{
let myBundlePath = Bundle.main.bundlePath
#if os(iOS)
let inMyFW = myBundlePath +
"/Frameworks" +
"/MyCustomFramework.framework"
#elseif os(OSX)
let inMyFW = myBundlePath +
"/Contents/Frameworks" +
"/MyCustomFramework.framework" + "/Versions/A/Resources"
#else
#endif
let pathInBundle = inMyFW+"/"+name
return pathInBundle
}
现在您可以在通常的图像加载调用中使用此路径。