I've created a reusable xib file that contains a table and it's being loaded in a TableView.swift
file like this:
我已经创建了一个可重用的xib文件,其中包含一个表,并将其加载到TableView.swift文件中,如下所示:
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
Bundle.main.loadNibNamed("TableView", owner: self, options: nil)
}
I'm only mentioning this to clarify that I am not confused about how to load the xib file
我只是提到这一点,以澄清我对如何加载xib文件并不感到困惑
I can easily load the reusable view in my RootViewController.swift
file by adding a view to the UIViewController
and giving that view a custom class like this:
我可以通过向UIViewController添加一个视图并为该视图提供如下自定义类,轻松地在我的RootViewController.swift文件中加载可重用视图:
and then creating an outlet for that view like this:
然后为这个视图创建一个这样的出口:
So here is my question:
所以这是我的问题:
Why am I not able to simply add the view like this:
为什么我不能简单地添加这样的视图:
let tableViewView = TableView()
When I do, I get an error that I don't totally understand:
当我这样做时,我得到一个我不完全理解的错误:
1 个解决方案
#1
2
You need to override the frame initializer as well.
您还需要覆盖帧初始值设定项。
Assuming your TableView
class is a UITableView
subclass, it should look something like this:
假设您的TableView类是UITableView子类,它应该如下所示:
class TableView: UITableView {
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
// any additional setup code
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// any additional setup code
}
}
Because you are trying to instantiate the table view programmatically, you need to give it an initializer for the frame, not only an initializer with a coder.
因为您尝试以编程方式实例化表视图,所以您需要为该帧提供初始化程序,而不仅仅是具有编码器的初始化程序。
#1
2
You need to override the frame initializer as well.
您还需要覆盖帧初始值设定项。
Assuming your TableView
class is a UITableView
subclass, it should look something like this:
假设您的TableView类是UITableView子类,它应该如下所示:
class TableView: UITableView {
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
// any additional setup code
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// any additional setup code
}
}
Because you are trying to instantiate the table view programmatically, you need to give it an initializer for the frame, not only an initializer with a coder.
因为您尝试以编程方式实例化表视图,所以您需要为该帧提供初始化程序,而不仅仅是具有编码器的初始化程序。