How to add a UITableView as a subview to a UIView in xib?

空扰寡人 提交于 2020-01-17 04:15:14

问题


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.



来源:https://stackoverflow.com/questions/41813208/how-to-add-a-uitableview-as-a-subview-to-a-uiview-in-xib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!