首页 > UITableViewDataSource中的cellForRowAtIndexPath如何实现?

UITableViewDataSource中的cellForRowAtIndexPath如何实现?

在controller中delegate了UITableViewDataSource以后,是必须实现这个方法以展示UITableView的。它的方法原型如下

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

能否结合例子具体解释下NSIndexPath的含义,另外与它想对应的还有一个必须实现的方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

这个section表示的又是什么呢?


先解释一下TableView的布局,一个TableView的内容两级,Section和Section中的Row,每个Row对应的视图成为TableViewCell。拿 设置.app 举例,如下图:

图中有两个Section
Section 0 中有6个Row -- 飞行模式~运营商
Section 1 中能看到3个Row -- 声音~桌面

再说问题里的两个方法。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;

这个方法返回的就是某个cell,可以自定义各种样式渲染,也可以用几种默认样式去渲染。
indexPath标示的是你要渲染的这个cell的位置,indexPath对象里有两个属性,section和row,顾名思义,可以定位某个cell。
注意:这个方法会在某个cell出现在屏幕中的时候被调用,而且是没出现一次就被调用一次。因为一个cell对象在屏幕可见区域消失的时候被回收,给其他出现在可见区域的cell复用。所以,在这个方法里渲染某个cell的时候,最好用个for循环或者什么的把cell清理干净。

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

这个方法,是在TableView生成的时候被调用(或者对tableView对象调用reloadData时),返回某个section中的row(cell)数量。
例如,在 设置.app 的界面里,应该是

switch (seciton) {
    0 :
        return 6;
    1 :
        return 3;
}
return 0;

1、NSIndexPath主要包含(NSUInteger)section(NSUInteger)row,每个row必然是属于一个section的,否则这个row没有意义,- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section里面就是表明各section有多少row
2、打开Contacts,里面的那些A、B、C...这样的标题就属于section headerheader + rows + footer就构成了一个完整的section. 可以通过- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section;进行定制header,footer类似

【热门文章】
【热门文章】