我的应用程序目前的结构是使用动态库来启用代码重用。我的动态库中存储了图像,因此可以轻松地在不同的应用程序目标之间共享它们。这在 iOS 中运行良好,因为我可以使用UIImage(named:, in:, compatibleWith:)
初始化程序从我的动态库中加载图像。但是,此初始化程序似乎在 watchOS 上不可用。是否有任何其他方法可以从 watchOS 上的动态库(使用不同的包)加载图像。顺便说一句,图像存储在资产目录中。
问问题
188 次
2 回答
2
我发现的解决方法是使用Bundle
'sresourceURL
获取Bundle
资源文件夹的根目录,然后使用Data(contentsOf:)
和从文件系统手动加载图像UIImage(data:)
。不过,这似乎不适用于资产目录。
于 2018-11-04T02:20:11.967 回答
1
我正在分享一段代码,它将从包中加载图像,它与 OSX、watchOS 和 iOS 兼容。如果您只想要 watchOS 的解决方案,请#elseif os(watchOS)
参与
#if os(OSX)
import AppKit
public typealias Image = NSImage
#elseif os(watchOS)
import WatchKit
public typealias Image = UIImage
#else
import UIKit
public typealias Image = UIImage
#endif
public extension String
{
func image(in bundle: Bundle? = Bundle.main) -> Image?
{
#if os(OSX)
guard let img = bundle?.image(forResource: self) else {
return nil
}
#elseif os(watchOS)
guard let resource = bundle?.resourceURL, let img = try? Image(data: Data(contentsOf: resource)) else {
return nil
}
#else
guard let img = Image(named: self, in: bundle, compatibleWith: nil) else {
return nil
}
#endif
return img
}
}
于 2019-05-09T18:07:40.413 回答