目前我正在努力创建 UIViewController
或 UINavigationController
的子类,并将 XIB 文件作为 View 。
当我从 Xcode 的菜单(New File -> Class -> With Nib... 等)创建所有内容时,我得到一个 XIB 但只有一个普通的 UIView
但我想要 UIViewController
。
我在某处读到,XIB 仅适用于 View ,您必须在代码中处理 Controller ,这是真的吗?因为你可以阅读 here可以将导航 Controller 组件插入到 XIB 中。但是我在使用本教程中的代码时遇到了一个问题 - 我得到了带有空 UINavigationBar
的空 View 。当我对常规 View Controller 执行相同的操作时,我会得到有关该 Controller 被多次使用的信息...
我并不是要强制 Interface Builder 做一些不寻常的事情,但我想知道这是否可能(修改内容 View 的 View Controller 组件会更容易和更好)?如果是,如何实现?
最佳答案
我刚刚检查了一下是否可能,令我惊讶的是它是可能的! 您可以在 Xibs 中拥有 UIViewController
测试在 XCode 10.1、Swift 4.2 中完成。
我以前从未使用过它,但我认为既然它为您提供了从项目库中选择 View Controller 的选项,那么它一定是可能的。我在我的 xib
中添加了一个,就像在 Storyboard 中一样,我将它与类链接,设置了 IBOutlet
和 IBAction
以及一切都运行得很好。
关键是像这样实例化它:
// Method inside the `UIViewController` you want to present our view controller from xib
// The xib file is `XibViewController.xib` and it has only one item inside - `UIViewController` with custom class set to `XibViewController`
guard let xibViewController = UINib(nibName: "XibViewController", bundle: nil).instantiate(withOwner: self, options: nil).first as? XibViewController else { return }
present(xibViewController, animated: true)
在这里你可以找到我的测试项目:https://github.com/stoqn4opm/XibViewController
关于ios - XIB 中的 UIViewController?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24769230/