I have a tableView and collectionView and to get indexPath i'm using below methods on tableViewCell and collectionViewCell (i dont want to use indexPathForSelectedRow/Item methods). Is there a way that I can make this generic?
Ideas please
// For Tableview
func getIndexPath() -> IndexPath? {
guard let superView = self.superview as? UITableView else {
return nil
}
let indexPath = superView.indexPath(for: self)
return indexPath
}
// For CollectionView
func getIndexPath() -> IndexPath? {
guard let superView = self.superview as? UICollectionView else {
return nil
}
let indexPath = superView.indexPath(for: self)
return indexPath
}
You could do this with two protocols, one that both
UITableView
andUICollectionView
conforms to, and the other that bothUITableViewCell
andUICollectionViewCell
conforms to.Really though, you shouldn't need a
getIndexPath
method on a table view cell. Cells should not know their index paths. I suggest you reconsider your design.