Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
782 views
in Technique[技术] by (71.8m points)

swift - Load image from iOS 8 framework

I'm trying to load an image from an iOS 8 framework that I'm writing (in Swift). I'm using Xcode 6 Beta 6

This code does not work (i.e. load image) if the image is stored in my framework's Images.xcassets:

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

If the image is stored in an Images.xcassets of a host application (that uses the framework), then the image is loaded properly (from code inside the framework).

I can see that the framework's Images.xcassets is included in the Copy Bundle Resources phase.

I'm also using a storyboard file as a resource in the framework; and this loads properly.

I've tried renaming the Images.xcassets of the framework to avoid some kind of naming collision with the host application, but this doesn't work either.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

While @Renatus answer is perfectly valid and addresses the core issue (bundle for framework needs to be specified), I wanted to post the solution I went with since it's slightly more direct:

Swift 3.0/4.0/5.0

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

Alternatively, you can use this pattern for non-class, aka non-"static", functions:

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

or this pattern for class functions:

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

These alternatives are better for cutting and pasting.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...