UIcollectionViewCell이 자신의 현재 indexPath를 알려면 직접 indexPath를 넣어 줄 수 있습니다.
final class TestCell: UICollectionViewCell {
//...
var indexPath: IndexPah
}
//UICollectionViewDataSource
func collectionView(
_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//...
guardelet cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TestCell") as? TestCell else {
fatalError("Reuse Error")
}
cell.indexPath = indexPath
return cell
}
좀 더 간단하게 indexPath를 알 수 있는 방법은 cell에서 자신의 superview를 찾는 것입니다.
extension UICollectionViewCell {
var indexPath: IndexPath? {
guard let collectionView = superview as? UICollectionView else { return nil }
return collectionView.indexPath(for: self)
}
}
Cell을 구현하는 곳에서 알 수 있게 됩니다.
final class TestCell: UICollectionViewCell {
//...
func didTapLikeButton() {
guard let indexPath = self.indexPath else { return }
self.parentListener.updateLike(at: indexPath)
}
}
이상입니다.