Skip to content

Instantly share code, notes, and snippets.

@martinhoeller
Last active May 10, 2020 09:16
Show Gist options
  • Save martinhoeller/124846f31f152254000331aed7e7c109 to your computer and use it in GitHub Desktop.
Save martinhoeller/124846f31f152254000331aed7e7c109 to your computer and use it in GitHub Desktop.
A Swift property wrapper for retreiving images from asset bundles
// inspired by https://stackoverflow.com/a/49205781/379776 and https://swiftbysundell.com/articles/property-wrappers-in-swift/
import UIKit
/*
Add something like this to your podspec
s.resource_bundles = {
'Assets' => ['MyPod/Assets/**/*.{xcassets}']
}
*/
extension Bundle {
static var assetsBundle: Bundle {
let frameworkBundle = Bundle(for: MyClass.self) // use any class in your framework
let assetUrl = frameworkBundle.url(forResource: "Assets", withExtension: "bundle")!
return Bundle(url: assetUrl)!
}
}
@propertyWrapper struct ImageAssetRetreivable<UIImage> {
let imageName: String
init(_ imageName: String) {
self.imageName = imageName
}
var wrappedValue: UIImage {
return UIKit.UIImage(named: imageName, in: .assetsBundle, compatibleWith: nil) as! UIImage
}
}
class ImageHelper {
@ImageAssetRetreivable("MyImage")
static var myImage: UIImage
@ImageAssetRetreivable("MyOtherImage")
static var myOtherImage: UIImage
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment