swift – 从iOS 8框架加载图像

前端之家收集整理的这篇文章主要介绍了swift – 从iOS 8框架加载图像前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试从我正在撰写的iOS 8框架中加载一个图像(在Swift中)。我正在使用Xcode 6 Beta 6

如果图像存储在我的框架的Images.xcassets中,则此代码不起作用(即加载图像):

let image = UIImage(named: "Background.png")

如果图像存储在主机应用程序(使用框架)的Images.x框架中,则图像将被正确加载(从框架内的代码)。

我可以看到框架的Images.xcassets包含在“复制包资源”阶段中。

我也在框架中使用storyboard文件作为资源;并正确加载。

我已经尝试重命名框架的Images.xcassets,以避免与主机应用程序发生某种命名冲突,但是这也不起作用。

虽然@Renatus答案是完全有效的,并解决了核心问题(框架需要指定的包),我想发布我去的解决方案,因为它稍微更直接:

Swift 3.0

let image = UIImage(named: "YourImage",in: Bundle(for: YOURFRAMEWORKCLASS.self),compatibleWith: nil)

Swift 2.2或2.3

let image = UIImage(named: "YourImage",inBundle: NSBundle(forClass: YOURFRAMEWORKCLASS.self),compatibleWithTraitCollection: nil)

或者,您可以将此模式用于非类,又称非“静态”函数

Swift 3.0

let image = UIImage(named: "YourImage",inBundle: Bundle(for: type(of: self)),inBundle: NSBundle(forClass: self.dynamicType),compatibleWithTraitCollection: nil)

或这种模式的类功能

Swift 3.0

let image = UIImage(named: "YourImage",in: Bundle(for: self),inBundle: NSBundle(forClass: self),compatibleWithTraitCollection: nil)

这些替代方法更适合切割和粘贴。

猜你在找的Swift相关文章