4

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:

enter image description here

and then creating an outlet for that view like this:

enter image description here

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:

enter image description here

John R Perry
  • 3,916
  • 2
  • 38
  • 62

1 Answers1

3

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.

nathangitter
  • 9,607
  • 3
  • 33
  • 42