【问题标题】:How to get uiTableView cell index on didSelectItem of collectionView cell如何在collectionView单元格的didSelectItem上获取uiTableView单元格索引
【发布时间】:2019-07-30 07:58:58
【问题描述】:

我有一个tableView,其中单元格包含collectionView。现在我想在选择集合视图单元格的任何单元格时获取 tableview 行索引

【问题讨论】:

  • 您可以将您的 tableViewCell indexPath.row 设置为 collectionView 的标签,并在 didSelectItem 中获取该标签

标签: swift uitableview uicollectionview


【解决方案1】:

创建UICollectionView 的子类并为其添加属性。

class MyCustomCollectionView: UICollectionView {
    var parentTableViewIndexPath: IndexPath?
}

在您的表格视图单元格中使用此集合视图

class MyCustomTableViewCell: UITableViewCell {
    @IBOutlet weak var customCollectionView: MyCustomCollectionView!
}

在表格的cellForRow 方法中,设置indexPath 属性

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "IDENTIFIER", for: indexPath) as! MyCustomTableViewCell
    cell.customCollectionView.parentTableViewIndexPath = indexPath
    //Any additional customisation
    return cell
}

在你的collectionView的didSelectItemAt中,像这样访问indexPath

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    guard let tableIndexPath = (collectionView as? MyCustomCollectionView)?.parentTableViewIndexPath else { return }
}

【讨论】:

    【解决方案2】:

    内部cellForRowAt

    cell.collectionView.tag = indexPath.row
    

    【讨论】:

    • 这不考虑具有多个部分的tableview
    • 在操作问题中请参阅“现在我想获取 tableview row 索引”他需要行而不是部分,这意味着他有一个包含 1 个部分的表
    猜你喜欢
    • 2019-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 1970-01-01
    • 2011-10-31
    • 2011-02-02
    相关资源
    最近更新 更多