我使用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却不能。那我该怎么办?
创建一个简短的静态类,我们称之为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
。