UITableViewDataSource
协议定义了UITableView
需要用数据填充自己的方法。它定义了几种可选的方法,但是有两点是需要(不可选):
// this method is the one that creates and configures the cell that will be
// displayed at the specified indexPath
– tableView:cellForRowAtIndexPath:
// this method tells the UITableView how many rows are present in the specified section
– tableView:numberOfRowsInSection:
而且,不需要下面的方法,但也是一个好主意来实现(数据源的一部分太)
现在
// this method tells the UITableView how many sections the table view will have. It's a good idea to implement this method even if you just return 1
– numberOfSectionsInTableView:
,该方法–tableView:cellForRowAtIndexPath:
会在你UITableView
运行一次,每可见细胞。例如,如果您的数据数组有10个元素,但只有5个可见,则–tableView:cellForRowAtIndexPath:
将运行5次。当用户向上或向下滚动时,将再次调用每个可见单元格的方法。
你说什么:“(该)数据源方法已经运行了10次以获得行数。”是不正确的。数据源方法–tableView:numberOfRowsInSection:
不运行10次以获取行数。实际上这个方法只运行一次。此外,此方法在–tableView:cellForRowAtIndexPath:
之前运行,因为表视图需要知道它必须显示多少行。
最后,方法–numberOfSectionsInTableView:
也运行一次,并且它在–tableView:numberOfRowsInSection:
之前运行,因为表视图需要知道段将如何存在。请注意这种方法不是必需的。如果你没有实现它,表格视图将假定只有一个部分。
现在我们可以将注意力集中在UITableViewDelegate
协议上。该协议定义了与UITableView
实际交互的方法。例如,它定义了管理单元格选择的方法(例如,当用户点击一个单元格时),单元格编辑(插入,删除,编辑等),配置页眉和页脚(每个部分可以有页眉和页脚), UITableViewDelegate
中定义的所有方法都是可选的。实际上,你根本不需要实现UITableViewDelegate
以获得表视图的正确基本行为,即显示单元格。
一些的UITableViewDelegate
最常用的方法是:
// If you want to modify the height of your cells, this is the method to implement
– tableView:heightForRowAtIndexPath:
// In this method you specify what to do when a cell is selected (tapped)
– tableView:didSelectRowAtIndexPath:
// In this method you create and configure the view that will be used as header for
// a particular section
– tableView:viewForHeaderInSection:
希望这有助于!
我认为你使用术语_data源method_和_delegate method_错误。你正在讨论的两种方法都是_data source_('')的一部分。这两件事情是分裂的:_data source_提供数据,_delegate_提供行为(对事件作出反应等)。通常都是使用_one_类实现的,所以它们经常混合在一起。 –
Tricertops