毫无疑问,您已经发现,与表行中的CollectionView交互不会触发tableView方法
tableView(_:didSelectRowAt:)
和
tableView.indexPathForSelectedRow
是
nil
因为没有选择行。你需要一种从地图上绘制地图的方法
collectionView
到
indexPath.row
这就包含了它。目前已知此信息
tableViewCell
安装时间。
在你的字典里加一本字典
Home2ViewController
这是一张地图
UICollectionView
争吵
Int
:
var collectionViewRow = [UICollectionView : Int]()
将条目添加到
tableView(_:cellForRowAt:)
在那里你知道
row
和
collectionView
:
collectionViewRow[cell.collectionView1] = indexPath.row
那么,只要你有机会
collectionView
,您可以查找其行:
let row = collectionViewRow[collectionView]!
以下是全部代码:
class Home2ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate {
var posts = [Post]()
var collectionViewRow = [UICollectionView : Int]()
override func viewDidLoad() {
// get posts elements here
//posts.append(element).......
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count // 4counts
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// let cell = DetailMutiTableViewCell()
let cell = tableView.dequeueReusableCell(withIdentifier: "DetailMutiTableViewCell", for: indexPath) as! DetailMutiTableViewCell
collectionViewRow[cell.collectionView1] = indexPath.row
cell.post = posts[indexPath.row]
cell.collectionView1.delegate = self
cell.collectionView1.dataSource = self
cell.collectionView1.reloadData()
return cell
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let row = collectionViewRow[collectionView]!
return posts[row].imageUrls.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MultiImagesCollectionViewCell", for: indexPath) as! MultiImagesCollectionViewCell
let row = collectionViewRow[collectionView]!
let photoUrlString = posts[row].imageUrls[indexPath.item] // âerror occured
let photoUrl = URL(string: photoUrlString)
cell.imageView1.sd_setImage(with: photoUrl)
return cell
}
}
笔记:
-
字典查找的强制展开不会失败,因为
collectionView
会在里面的。如果你想用
if let
,你需要决定当你没有吵架时该做什么(这是不应该发生的)。
-
如果表允许编辑,此方法可能会失败(用户可以重新排列行的顺序或删除行)。如果你不支持编辑,那么这就可以了。要支持编辑,可以将字典更改为
[UICollectionView : UITableViewCell]
.然后,如果
UICollectionView
,你可以查阅
cell
,然后打电话
let indexPath = tableView.indexPath(for: cell)
得到
indexPath
然后你的争吵就结束了
是的。一行
.