简体   繁体   English

如何将数据从 uitableviewcontroller 发送到 uitableviewcell

[英]how to send data from uitableviewcontroller to uitableviewcell

I have the following situation我有以下情况

A TableViewController (ExploreViewController) has custom cells - CategoryTableViewCell. TableViewController (ExploreViewController) 具有自定义单元格 - CategoryTableViewCell。 Each cell has a collection view with UICollectionViewCells.每个单元格都有一个带有 UICollectionViewCells 的集合视图。

I would like the CategoryTableViewCell to contact the ExploreViewController when displaying the collection view cells to determine what data it needs to display.我希望 CategoryTableViewCell 在显示集合视图单元格时联系 ExploreViewController 以确定它需要显示哪些数据。 The data is dependent on the index path row of the table view cell and on the index of the collection view cell.数据取决于表格视图单元格的索引路径行和集合视图单元格的索引。

How can I accomplish this using delegates?我怎样才能使用委托来实现这一点?

I wouldn't do it that way.我不会那样做的。 I would pass the data each cell needs to it as a model object in the table view controller's cellForRow(at:) method.我会在表格视图控制器的cellForRow(at:)方法中将每个单元格需要的数据作为 model object 传递给它。 If a cell's data changes, pass it a new model object.如果单元格的数据发生更改,请将新的 model object 传递给它。 Then the cell can use that model data to respond to data source calls from its child collection view.然后单元格可以使用该 model 数据来响应来自其子集合视图的数据源调用。

If you are determined to use the delegate pattern, or something like it:如果您决定使用委托模式或类似模式:

Let's call it a data source instead of a delegate.让我们称它为数据源而不是委托。 Design a CategoryTableViewCellDataSource protocol.设计一个 CategoryTableViewCellDataSource 协议。 When you create a CategoryTableViewCell, set the table view controller as its data source.创建 CategoryTableViewCell 时,将表视图 controller 设置为其数据源。

Have the cell ask it's data source for the data to display.让单元格询问它的数据源以显示数据。 The delegate protocol would use the cell's position to figure out it's index path, and then fetch the data from the model and return it.委托协议将使用单元的 position 来确定它的索引路径,然后从 model 获取数据并返回。 (You'd find the midpoint of the cell's content view, convert the point to the table view's coordinate system, and then use the table view's indexPathForRow(at:) method to figure out the index path. (你会找到单元格内容视图的中点,将该点转换为表格视图的坐标系,然后使用表格视图的indexPathForRow(at:)方法找出索引路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM