iOS:如何在框架内加载xib

时间:2018-08-16 15:09:44

标签: ios swift cocoa-touch xib

我使用CocoaPod创建了一个包含xib视图的新框架,以及一个测试该框架的测试应用程序。测试应用程序包含一个按钮,该按钮调用该框架并显示xib。

起初,我在此行在框架内崩溃:

if let myView = Bundle.main.loadNibNamed("myCustomXib", owner: self, options: nil)?.first as? myCustomXibClass 

日志:Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle </Users/User/Library/Developer/CoreSimulator/Devices/F7B870D5-4CEC-4CC7-9C76-75DF1408A26C/data/Containers/Bundle/Application/20E3D273-315C-43EE-95CC-9B00B8EE8B6E/appDemo.app> (loaded)' with name 'myCustomXib''

然后我用以下命令更改该行:

let bundle = Bundle(identifier:"com.framework.identifier")

    if let myView = bundle?.loadNibNamed("myCustomXib", owner: self, options: nil)?.first as? myCustomXibClass {

崩溃消失了,但是什么也没显示。

这是我在podspec中添加源的方式:

  s.resources   = ["**/*.{storyboard,xib}", "Assets.xcassets"]

,我将所有文件保存在本地开发窗格中。故事板工作正常,但xib却不能。那我该怎么办呢?

1 个答案:

答案 0 :(得分:0)

创建一个简短的静态类,我们将其称为 MyFrameworkBundle

public final class MyFrameworkBundle {
    public static let main: Bundle = Bundle(for: MyFrameworkBundle.self)
}

对于 WindowController 中的 XIB

public class MyFrameworkWindowController: NSWindowController {

    override public var windowNibName: String! {
        return "MyFrameworkWindowController"
    }

    public init() {
        super.init(window: nil) 

        /* Load window from xib file */
        MyFrameworkBundle.main.loadNibNamed(windowNibName, owner: self, topLevelObjects: nil)
    }

    // Override this as required per the class spec
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented. Use init()")
    }

    override public func awakeFromNib() {
        //Do your stuff
    }
}

如果您是从“ 开发包”目录本地运行代码,请在首次运行前使用CMD+SHIFT+K