How to add a UITableView as a subview to a UIView

2019-09-14 23:37发布

问题:

I have a custom view that I built using xib file. In this custom view, there is a UIView where I would like to add a static UITableView as a subview. The UITableView to be shown here is present on the storyboard and associated to a UITableViewController. I did the following:

let vc = (UIStoryboard(name: "Main", bundle: nil))
    .instantiateViewControllerWithIdentifier("tableController") as! TableController
vc.loadViewIfNeeded()
table = vc.table // this is an outlet, I'm sure it is not nil
table.delegate = vc
table.dataSource = vc
table.backgroundColor = UIColor.greenColor()
containerView.addSubview(table)

I can see the green background on my custom view but the table cells are not being displayed

I know the outlet to the table is not nil because when debugging if I inspect the table variable using the Quick Look icon below the console, I can see the table.

UPDATE

I realized my approach was not a good one.

I achieved the results I wanted by making my View a subview of UITableViewDataSource and UITableViewDelegate and programmatically creating a UITable and a required TableViewCell. Crazy amounts of codes!!

回答1:

The UITableView to be shown here is present on the storyboard and associated to a UITableViewController.

In that case, what you're doing is totally illegal and that's why it isn't working. You cannot just call instantiateViewControllerWithIdentifier, grab the view controller's view, and stuff that view into the interface with addSubview.

After all, think about it: if you do that, what happens to the view controller? It goes out of existence, and you've got a totally nonfunctional view.

There is a rigorous dance that you are required to do in order to make the TableController a child view controller of self (the current view controller — and you are not doing the dance.