UITableView中的数据源和委托如何工作?

YU *_*ENG 1 objective-c uitableview ios

我是ios开发的新手.当我使用UITableView时,我实现了数据源和委托.喜欢以下两种方法:

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

 // Delegate method
 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
Run Code Online (Sandbox Code Playgroud)

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

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

Lui*_*ien 8

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:
Run Code Online (Sandbox Code Playgroud)

此外,不需要以下方法,但也是一个好主意(也是数据源的一部分)

// 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:
Run Code Online (Sandbox Code Playgroud)

现在,该方法–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:
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!