Last active
January 15, 2020 13:56
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
can easily be used like:
tableView.indexPathForCellWithSubview(cellSubview)