How to use images asset catalog in cocoapod library for iOS

前端 未结 11 2402
粉色の甜心
粉色の甜心 2020-12-15 16:38

I have a cocoapod library which contains assets in 2 formats:

  • a .storyboard
  • XCode asset catalog .xcassets (with images)

my podsp

11条回答
  •  盖世英雄少女心
    2020-12-15 17:32

    My own solution to the issue with CocoaPods. Instead of mucking with UIImage, I added a method to Bundle instead. The method attempts to locate an inner bundle of a given name, but falls back to the original bundle. This allows the code to work in both the application code using pods, as well as the pod code itself.

    extension Bundle {
    
        /**
         Locate an inner Bundle generated from CocoaPod packaging.
    
         - parameter name: the name of the inner resource bundle. This should match the "s.resource_bundle" key or
           one of the "s.resoruce_bundles" keys from the podspec file that defines the CocoPod.
         - returns: the resource Bundle or `self` if resource bundle was not found
        */
        func podResource(name: String) -> Bundle {
            guard let bundleUrl = self.url(forResource: name, withExtension: "bundle") else { return self }
            return Bundle(url: bundleUrl) ?? self
        }
    }
    

    Then in the viewDidLoad method or wherever else you have your image setting code, put something like this, where "ClassFromPod" refers to a Swift class from a CocoaPod, and "ResourceName" is the name of the inner bundle within the pod (you should be able to see the bundles using Xcode project navigator in "Pods/Projects" -- embedded bundles have a LEGO icon and have a "bundle" suffix.)

    super.viewDidLoad()
    let bundle = Bundle(for: ClassFromPod.self).podResource(name: "ResourceName")
    img1 = UIImage(named: "FancyBase", in: bundle, compatibleWith: nil)
    img2 = UIImage(named: "FancyHandle", in: bundle, compatibleWith: nil)
    

    As you can see, the UIImage API remains the same, only the bundle being used is different depending on what it finds at runtime.

提交回复
热议问题