2

我是ios开发新手。当我使用 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 次以获取行数。我们使用数据源的原因是为了管理使用集合视图呈现的内容。所以我的问题是,数据源如何管理内容?数据源对象是否存储所有这些表视图信息?(因为它在委托之前运行并且它知道表视图的总数)如果它存储表视图的信息,它似乎与委托冲突,因为表视图委托不保存任何数据, 正确的?

还有一个问题是我们在什么情况下只使用数据源?因为我们可以创建自定义委托吗?是否存在我们只创建自定义数据源的情况?因为我看到数据源总是带有委托......谢谢!

4

2 回答 2

9

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:

希望这可以帮助!

于 2013-10-21T18:17:59.933 回答
1

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

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

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

于 2013-10-21T17:55:48.337 回答