Pod库图片资源获取方式

2023-05-16  本文已影响0人  吕建雄

podspec中引入图片资源的方式:

s.resource_bundles = {

    'PodName' => ['PodName/Assets/*.*']

  }

当打包后会发现直接使用UIImage(named: "picname")这种方式获取不到图片,是因为使用resource_bundles后,图片资源会包含在.bundle文件中

解决方案:

@objc public extension UIImage{

    ///获取 pod 库中 bundle 图片资源

    convenience init?(named name: String, podName: String, bundleName: String? =nil) {

        let bName = bundleName ?? podName

        //如果直接在bundle中能找打,那么直接使用即可

        if let image = UIImage(named:"\(bName).bundle/\(name)"),let cgImage = image.cgImage{

            self.init(cgImage: cgImage)

        }else{

            var filePath = Bundle.main.resourcePath! +"/Frameworks/\(podName).framework/\(bName).bundle"

            guard let bundle = Bundle(path: filePath) else{

                //处理:静态库图片展示,静态库相比动态库,没有.framework:Frameworks/\(podName).framework

                filePath = Bundle.main.resourcePath! +"/\(bName).bundle"

                if let staticBundle = Bundle(path: filePath) {

                    self.init(named: name,in: staticBundle,compatibleWith:nil)

                    return

                }

                return nil

            }

            self.init(named: name,in: bundle,compatibleWith:nil)

        }

    }

}

上一篇 下一篇

猜你喜欢

热点阅读