【问题标题】:Communication between UICollectionViewCell and UICollectionView swift files [duplicate]UICollectionViewCell 和 UICollectionView swift 文件之间的通信 [重复]
【发布时间】:2021-02-20 18:01:14
【问题描述】:

我有两个文件。第一个是包含 UICollectionView 的 UIViewController。第二个是 UICollectionViewCell,它类似于单元格笔尖的 ViewController。它管理单元格内的所有操作,例如,如果用户单击单元格内的点赞按钮。

当用户单击赞按钮时,我会打印包含赞按钮的单元格的 IndexPath。所有单元格都包含一个赞按钮,但我想知道用户单击赞按钮的单元格的 IndexPath。

我的问题是如何将此 IndexPath 传达给 UIViewController?我想这样做是因为我的 UIViewController 存储了整个数据(在一个数组中),并且我想使用 IndexPath 访问这些数据的特定部分。另一种可能性是将这些数据存储在 UICollectionViewCell 文件中,但这不是一个好方法。

【问题讨论】:

  • swiftiest 方式是一个回调闭包,它传递可以从中获取索引路径的单元格。如果集合视图项的顺序永远不会改变,您甚至可以使用捕获的索引路径。
  • 这是我前段时间做的一个例子:stackoverflow.com/a/64508719/14351818

标签: ios swift xcode uicollectionview uicollectionviewcell


【解决方案1】:

我真的很难找到解决方案,你帮了我很多。非常感谢你们!回调闭包是解决这个问题的正确方法。这是我的解决方案:

//UICollectionViewCell
var saveProductLike: ((_ index: Int) -> Void)?
@IBAction func likedButtonClicked(_ sender: UIButton) {
    print("Liked button clicked!")
    let productArrayIndex = calculateProductArrayIndex(for: sender)
    saveProductLike?(productArrayIndex!)
}

//UIViewController
cell.saveProductLike = { (index) -> Void in
    print(index)  
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多