39.打包包含xib的framework库

2017-02-27  本文已影响39人  noonez

平时我们加载xib都是使用Bunlde.main,这样做是没错的,因为我们使用的xib就在主项目的Bundle中。
比如我现在加载一个叫"FView"的xib,FView是个UIView

func addXib() {
        let views = Bundle.main.loadNibNamed("FView", owner: self, options: nil)!
        let tmp = views.first as! UIView
        tmp.frame.size = CGSize(width: 300, height: 300)
        view.addSubview(tmp)
 }

但是如果是在要发布的framework库中,还这样加载xib,那么别的地方使用这个framework就会引起崩溃。因为库中的xib并不在主项目的Bunlde中,而是在framework库中的Bundle中。
要正确加载xib,只需要将加载xib的地方改下,加载时改用当前项目的Bundle,这样app就不会去Bundle.main中找xib了。

let views = Bundle(for: type(of:self)).loadNibNamed("TestView", owner: self, options: nil)
        let testView = views?.first as! UIView
        testView.frame.size.width = self.frame.width
        addSubview(testView)

这是Bundle构造函数描述

Bundle.init(for aClass: AnyClass)

Description

Returns the NSBundle object with which the specified class is associated.(返回与指定的类相关联的NSBundle对象。)

源码:https://github.com/ghyh22/XibFramework

上一篇 下一篇

猜你喜欢

热点阅读