【发布时间】:2019-02-26 22:10:42
【问题描述】:
我有一个 tableView,每个 tableViewCell 中都有 collectionViews。 每个 tableViewCell 都是电影类型,而 collectionViewCells 就是电影。 我试图告诉 collectionView 它是哪个 TableView indexPath,以便它可以显示正确的数据。
我遇到的问题是,当您滚动浏览 collectionView(和 TableView)时,数字会发生变化(我在 collectionView 单元格中有一个标签,显示 TableView indexPath.row)。此外,如果我在第一个 tableView 单元格中滚动到 collectionView 的末尾,那么第 4 个左右的 tableViewCell 中的 collectionViewCell 也将滚动到末尾,就好像它们是“链接的”一样。
为了获得嵌套的布局,我正在关注这个 tut https://youtu.be/4XnXHov2lQU 我最初是从 TableViewCell 类中设置 collectionView,但正如视频中所述,这不符合 MVC。
要获得tableViewIndexPath,我只需在TableView 中设置一个变量cellForRowAt,然后将collectionView 中的标签设置为此。
什么是正确的方法,因为我已经看到了其他问题并在此发布了答案,但几乎所有问题都给出了相同的问题。
编辑 - TableViewController.swift
class TableViewController: UITableViewController {
var tableViewIndexPath = Int()
override func viewDidLoad() {
super.viewDidLoad()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 230
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableViewCell", for: indexPath) as! tableViewCellClass
tableViewIndexPath = indexPath.row
cell.collectionView.dataSource = self
cell.collectionView.reloadData()
return cell
}
}
extension TableViewController : UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewCell", for: indexPath)
let title = cell.viewWithTag(4) as! UILabel
title.text = String(tableViewIndexPath)
return cell
}
}
TableViewCellClass.swift
class tableViewCellClass: UITableViewCell {
@IBOutlet weak var collectionView: UICollectionView!
var indexPathForCell: IndexPath?
override func prepareForReuse() {
self.collectionView.contentOffset = .zero
self.collectionView.reloadData()
}
}
【问题讨论】:
标签: ios swift uitableview uicollectionview