Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save danielgalasko/ab78ed6359951d23d461 to your computer and use it in GitHub Desktop.
Save danielgalasko/ab78ed6359951d23d461 to your computer and use it in GitHub Desktop.
Easily retrieve the indexPath of cell's subview in UITableView. Great for button taps and TextFields
extension UITableView {
/**
Returns an index path identifying the row and section
of the cell containing the provided view
:param: cellSubview A subview of any given UITableViewCell in the table. Typically this is either a `UIButton` or `UITextField`
*/
func indexPathForCellWithSubview(cellSubview: UIView) -> NSIndexPath? {
let cellFrame = convertRect(cellSubview.bounds, fromView: cellSubview)
let cellCenter = CGPoint(x: CGRectGetMidX(cellFrame), y: CGRectGetMidY(cellFrame))
return indexPathForRowAtPoint(cellCenter)
}
}
extension UICollectionView {
/**
Returns an index path identifying the row and section
of the cell containing the provided view
:param: cellSubview A subview of any given UICollectionViewCell in the collectionView. Typically this is either a `UIButton` or `UITextField`
*/
func indexPathForCellWithSubview(cellSubview: UIView) -> NSIndexPath? {
let cellFrame = convertRect(cellSubview.bounds, fromView: cellSubview)
let cellCenter = CGPoint(x: CGRectGetMidX(cellFrame), y: CGRectGetMidY(cellFrame))
return indexPathForItemAtPoint(cellCenter)
}
}
@danielgalasko
Copy link
Author

can easily be used like: tableView.indexPathForCellWithSubview(cellSubview)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment