从 collectionView 单元格中获取和更新 UITableView 单元格单击

Posted

技术标签:

【中文标题】从 collectionView 单元格中获取和更新 UITableView 单元格单击【英文标题】:fetch & update UITableView cells from a collectionView cell click 【发布时间】:2020-12-26 10:56:46 【问题描述】:

说,我有一个带有tableView 的 ViewControllerA,并且 tableView 使用 xib 方法创建和加载了它的标题视图,并且该 headerView 包含一个 .horizontal 滚动方向 collectionView,我的问题是如何我在 headerView 内的collectionView 发起的点击时更新了我的tableView 的内容?

类似的例子如下图所示:

比如说,我点击了Tableview的HeaderView内UICollectionViewCell上的“Research”标签,tableView重新加载了“Research”的数据,接下来我点击了“Design”标签,tableView重新加载了自身并显示数据对于“设计”..这样的事情可能吗?我被困在这里了.. .

【问题讨论】:

一个简单的处理方法是使用委托模式 好吧,既然我被困在这里,如果可以的话,你能推荐一个吗? 如果碰巧你会怎么做? 您可以使用纯集合视图并使用视图布局,但实现起来太复杂 看看这个***.com/questions/54552625/…和***.com/questions/35448927/… 【参考方案1】:

将标题UICollectionView 链接到情节提要中的插座,然后实现所有必需的委托方法。 添加这个委托方法:

class ViewController: UIViewController

var categories = [String]()
var discoverData = [discoverModel]()
var tableView: UITableView!
override func viewDidLoad() 
    super.viewDidLoad()




extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 
    categories.count


func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 
    //code to initialize cells of header collecionView


func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) 
    let selectedCategory = categories[indexPath.row]
    let cellToReload = discoverData.filterreturn $0.serviceName == selectedCategory[0]
    
    guard let indexPathsOfCellToRealod = discoverData.firstIndex(of: cellToReload) else  return 
    tableView.reloadRows(at: [IndexPath(index: indexPathsOfCellToRealod)], with: .automatic)



struct discoverModel: Equatable
   var image: UIImage
   var serviceName: String
   var name: String
   var description: String

要完成这项工作,只需将标准的 UITableView 委托方法添加到您的 ViewController

【讨论】:

以上是关于从 collectionView 单元格中获取和更新 UITableView 单元格单击的主要内容,如果未能解决你的问题,请参考以下文章

从popover返回后如何在collectionview单元格中填充文本字段

一个collectionview单元格中有两个UIImage?

在自定义 collectionview 单元格中填充图像而不会闪烁

普通 CollectionView 单元格中的动态 CollectionView 单元格

多个tableView单元格中的多个collectionView

子视图在 collectionView 单元格中重复?