iOS:如何在框架内加载xib [英] iOS: How to load a xib inside framework
问题描述
我使用CocoaPod创建了一个包含xib视图的新框架,以及一个测试该框架的测试应用程序.测试应用程序包含一个按钮,该按钮调用该框架并显示xib.
I created a new Framework containing a xib view using CocoaPod, and a test application to test that framework. The test application contains one button that makes a call to that framework and to show the xib.
起初,我在这一行的框架内崩溃:
At first I had a crash inside the framework at this line:
if let myView = Bundle.main.loadNibNamed("myCustomXib", owner: self, options: nil)?.first as? myCustomXibClass
日志:由于未捕获的异常"NSInternalInconsistencyException"而终止应用程序,原因:无法在捆绑包中加载NIB:" NSBundle</Users/User/Library/Developer/CoreSimulator/Devices/F7B870D5-4CEC-4CC7-9C76-75DF1408A26C/data/Containers/Bundle/Application/20E3D273-315C-43EE-95CC-9B00B8EE8B6E/appDemo.app>(已加载)',名称为"myCustomXib"
然后我用以下命令更改该行:
Then I changed that line with this:
let bundle = Bundle(identifier:"com.framework.identifier")
if let myView = bundle?.loadNibNamed("myCustomXib", owner: self, options: nil)?.first as? myCustomXibClass {
然后崩溃消失了,但是什么也没显示.
and the crash is gone, but nothing is displaying.
这是我在podspec中添加源的方式:
here is how I added the sources in my podspec:
s.resources = ["**/*.{storyboard,xib}", "Assets.xcassets"]
,我将所有文件保存在本地开发窗格中.故事板工作正常,但xib效果不佳.那我该怎么办?
and I get all the files in my local development pod. The storyboards work perfectly, but not the xib. So how can I do ?
推荐答案
创建一个简短的静态类,我们将其称为 MyFrameworkBundle :
Create a short static class, let's call it 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
.
If you run your code locally from a "Development Pods" directory, use CMD+SHIFT+K
before running first time.
这篇关于iOS:如何在框架内加载xib的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!