0

I have two files. First one is a UIViewController that contains a UICollectionView. Second one is a UICollectionViewCell that is something like a ViewController for the cell nib. It manages all actions inside the cell for example if the user clicks a like button inside a cell.

When the user clicks the like button I print the IndexPath of the cell that contains the like button. All cells contain a like button but I want to know the IndexPath of the cell where the user clicked the like button.

My Problem is how can I communicate this IndexPath to the UIViewController? I want to do it because my UIViewController stores the whole data (in an array) and I want to get access to specific part of this data using IndexPath. An other possibility is also to store this data inside the UICollectionViewCell file but it is not a good way.

Kinuhatek
  • 85
  • 2
  • 10
  • 1
    The *swiftiest* way is a callback closure which passes the cell where you can get the index path from. If the order of the collection view items never changes you can even use the captured index path. – vadian Nov 08 '20 at 17:35
  • 2
    Here's an example I made a while ago: https://stackoverflow.com/a/64508719/14351818 – aheze Nov 08 '20 at 17:53

1 Answers1

0

I really had problems to find a solution, you helped me a lot. Thank you very much guys! Callback closure is the right way to solve this problem. This is my solution:

//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)  
}
Kinuhatek
  • 85
  • 2
  • 10