如何在xib中将UITableView作为子视图添加到UIView? [英] How to add a UITableView as a subview to a UIView in xib?
问题描述
我有一个使用xib
文件构建的自定义视图.在此自定义视图中,有一个UIView
,我想在其中添加一个静态UITableView
作为子视图.此处显示的UITableView
存在于storyboard
上并与UITableViewController
关联.我做了以下事情:
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
我知道该表的出口不是零,因为在调试时,如果我使用控制台下方的Quick Look
图标检查table
变量,则可以看到该表.
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.
更新
我意识到我的方法不是一个好方法.
I realized my approach was not a good one.
通过将View设为UITableViewDataSource
和UITableViewDelegate
的子视图,并以编程方式创建UITable
和必需的TableViewCell
,从而获得了所需的结果.疯狂的代码量!!
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!!
推荐答案
要在此处显示的UITableView存在于情节提要上,并与UITableViewController关联.
The UITableView to be shown here is present on the storyboard and associated to a UITableViewController.
在这种情况下,您正在做的事情完全是非法的,这就是为什么它不起作用的原因.您不能只调用instantiateViewControllerWithIdentifier
,获取视图控制器的视图以及使用addSubview
将视图填充到界面中.
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.
为了使TableController成为self
的子视图控制器(当前的视图控制器,您必须执行一次严格的舞蹈,并且您没有在做舞蹈.
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.
这篇关于如何在xib中将UITableView作为子视图添加到UIView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!