How to add reusable custom views programmatically? (Swift)
ios, nscoding, swift, uitableview, xib
Solution
You need to override the frame initializer as well.
Assuming your `TableView` class is a `UITableView` subclass, it should look something like this:
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.
Problem
I've created a reusable xib file that contains a table and it's being loaded in a `TableView.swift` file like this: ``` 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 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: 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: