2013-10-21 35 views
1

我是ios开发新手。当我使用UITableView时,我实现了数据源和委托。像以下两种方法:UITableView中的数据源和委托如何工作?

// Data source method 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 

// Delegate method 
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 

但是,如果我理解正确,表格视图不保存任何数据,并且只存储足够的数据来绘制当前可见的行。因此,例如,如果我在表中有10个数据,并且当前只显示5个数据。这意味着委托方法运行5次,但在委托方法运行5次之前,数据源方法已经运行了10次以获取行数。我们使用数据源的原因是管理使用集合视图呈现的内容。所以我的问题是,数据源如何管理内容?数据源对象是否存储了所有这些表视图信息?(因为它在委托之前运行并且它知道表视图的总数)如果它存储表视图的信息,由于表视图委托不包含任何数据,它似乎与委托相冲突, 对?

还有一个问题是我们在什么情况下只使用数据源?因为我们可以创建自定义委托吗?有没有情况我们只创建自定义数据源?由于我已经看到数据源总是与代表....谢谢!

+0

我认为你使用术语_data源method_和_delegate method_错误。你正在讨论的两种方法都是_data source_('')的一部分。这两件事情是分裂的:_data source_提供数据,_delegate_提供行为(对事件作出反应等)。通常都是使用_one_类实现的,所以它们经常混合在一起。 – Tricertops

回答

7

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: 

希望这有助于!

+0

好的解释.....非常感谢。 –

1

数据源和委托是模型 - 视图 - 控制器范例的两个独立部分。除非需要/想要,否则不需要连接委托人。

委托方法根本不为表提供数据。数据源具有表格的实际数据(存储在数组或字典或其他内容中)。

您似乎很困惑,因为您列出了- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath作为委托方法,但它实际上是数据源协议的一部分。

相关问题