如何使用 xib 子类化 UIViewController 并添加更多视图
我有一个连接到它的 .xib 的 BaseViewController,并希望在故事板中使用 SubViewController 对其进行子类化以添加更多视图。我已经对 UIView 进行了类似的设置,但它不适用于 UIViewcontroller。 没有特定的代码,我只看到从故事板设计的 SubViewController“屏幕”。 BaseViewController xib 未加载。
如果我将下面的代码放在 BaseViewController 中,那么我可以看到其中的所有视图,但不能看到 BaseViewController
public required init?(coder: NSCoder) {
super.init(coder: coder)
let bundle = Bundle(for: type(of: self))
var myCustomView = UINib(nibName: "BaseViewController", bundle: bundle).instantiate(withOwner: self, options: nil)[0] as? BaseViewController
}
有了 BaseViewController 中的这段代码,我得到“无法将自身添加为子视图”:
let bundle = Bundle(for: type(of: self))
guard let view = bundle.loadNibNamed("BaseViewController", owner: self, options: nil)?.first as? UIView else {
return
}
self.view.addSubview(view)
view.frame = self.view.bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
目前我只能有 BaseViewController 或 SubViewController 视图屏幕,但不能同时显示两者。目标是在 SubViewController 视图后面设置 BaseViewController xib。
这可以用 UIViewcontroller 来完成还是我做错了?
I have a BaseViewController connected to it's .xib and want to subclass it with SubViewController in my storyboard to add more views. I already have do similar setup with UIView but it doesn't work for UIViewcontroller.
With no particular code, i only see SubViewController "screen" designed from storyboard. The BaseViewController xib is not loaded.
If i put below code in BaseViewController then i can see all the views from it but not from BaseViewController
public required init?(coder: NSCoder) {
super.init(coder: coder)
let bundle = Bundle(for: type(of: self))
var myCustomView = UINib(nibName: "BaseViewController", bundle: bundle).instantiate(withOwner: self, options: nil)[0] as? BaseViewController
}
With this code in BaseViewController i get "Can't add self as subview":
let bundle = Bundle(for: type(of: self))
guard let view = bundle.loadNibNamed("BaseViewController", owner: self, options: nil)?.first as? UIView else {
return
}
self.view.addSubview(view)
view.frame = self.view.bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
For the moment i can only have either BaseViewController or SubViewController views on screen but not both. The goal is to have BaseViewController xib setup behind the SubViewController views.
Can this be done with UIViewcontroller or does i do it the wrong way ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
经过大量测试后,不可能子类化 UIViewcontroller 并保留基本代码并向其添加新的子类代码。
After a lot of testing, it's just not possible to sublcass a UIViewcontroller and keep both the base code and add the new subclassed code to it.