自定义UItableView的实现以及组件不可见的问题及解决
有时需要写一个自定义的UITableView,这里的自定义UITableView指的是自定义列表内容,通常就是实现一个UITableViewCell的子类,如MyTableViewCell。下面先来实现一个自定义组件。
STEP 1.
新建一个Empty Application,这里我就叫MyTableViewTest,勾选ARC选项。
STEP 2.
新建一个ViewController对象,注意不需要生成xib文件,这里我就叫MyViewController
STEP 3.
在AppDelegate.m中指定MyViewController为程序的rootViewController
STEP 5.
new一个UITableViewCell的子类,就叫MyUITableViewCell,这个类其实更像一个容器类。并对xib文件中的UILabel和UIButton进行连接。这里有一个需要注意的地方。就是MyUITableViewCell的File's owner是什么并不重要(比如可以是NSObject),只需要将Cell上的UIButton和UILable连接到Cell上即可。怎么连接呢?先在MyUITableViewCell.h中定义对应的property属性,如myLabel和myButton。然后右击UILable弹出一个黑色的框框,选择其中的Referencing Outlets下的New Referencing Outlet,拖到鼠标到左侧的组件MyUITableViewCell上,此时会自动弹出一个黑色的框框,选中myLabel即可。
详见下图:
![]()
这里必须讨论一下为什么将组件链接到MyUITabelViewCell上,而不是File's owner。其实刚开始我是直接把组件链接到File's owner上的,但是这样之后就直接报错了。于是就google,找了一段解释,可以看看
Normally you don't have to bother about the File's owner in that case, because when thetableView
instantiate the cell from theUINib
you provided / associated with thereuseIdentifier
, it will load all the top-level objects of the nib, and use only the first top-level object that is of classUITableViewCell
(or maybe juste the first top-level-object regardless of the class? but in general you only have yourUITableViewCell
in your XIB anyway — without counting theFile's Owner
and theFirst Responder
which are only "proxies").In fact, when the
tableView
try to dequeue a cell and don't find a reusable one, so create a new one for you, it uses theUINib
you provided quite like this:NSArray* topLevelObjects = [self.cellNib instantiateWithOwner:nil options:0];cell = [topLevelObjects objectAtIndex:0];
(That's of course a simplified version just to show the principle, I don't know if it actually call only these exact lines, but it should be quite close)
So the
File's Owner
is not used in this particular case, and you only need to put a simple customUITableViewCell
as the only top-level-object of your XIB file next to the existingFile's Owner
anfFirst Responder
(that, again, are only "proxies" / "External Objects references" and won't be instantiated and won't be part of the top-level-objects returned byinstantiateWithOwner:options:
).原文地址:http://stackoverflow.com/questions/12590471/uitableview-registernibforcellreuseidentifier
STEP 6.
因为没有为MyViewController生成xib文件,所以我们需要在MyViewController的代码中来手动添加组件,这里在viewDidLoad方法中添加。那么出于调用方便的考虑,可以在MyViewController.h中定义UITableView的属性。当然不要忘了实现UITableView对应的Delegate和Datasource协议。下面是 MyViewController.h:
O啦~~~,写了挺久的,终于好啦
转帖请保留出处:http://write.blog.csdn.net/postedit/12745165
工程下载地址:http://download.csdn.net/detail/u011638883/6404331
谢谢!!