I want to detect button tap on a UITableViewCell where the parent UITableView consists of multiple sections.
I was able to do it in the case of single section, but I
A more direct way to get the index path without using CGPoint
and making assumptions about UI is to look at the .superview
. I'd imagine this is more reliable in practice.
- (myTableViewCell *)cellContainingView:(UIView *)view
{
do {
view = view.superview;
} while (view != nil && ![view isKindOfClass:[myTableViewCell class]]);
return (myTableViewCell *)view;
}
Then you can simply do this in the button action:
- (IBAction)myButtonPressed:(id)sender
{
myTableViewCell *cell = [self cellContainingView:(UIView *)sender];
NSIndexPath *path = [self.tableView indexPathForCell:cell];
}
Swift 5
let touchPoint: CGPoint = sender.convert(.zero, to: tableViews)
let clickedButtonIndexPath = self.tableViews.indexPathForRow(at: touchPoint)
if(clickedButtonIndexPath != nil)
{
NSLog("index path.section ==%ld", Int(clickedButtonIndexPath!.section))
NSLog("index path.row ==%ld", Int(clickedButtonIndexPath!.row))
}
Objective-C
-(void)addItem:(UIButton*) sender
{
CGPoint touchPoint = [sender convertPoint:CGPointZero toView:mainTable]; // maintable --> replace your tableview name
NSIndexPath *clickedButtonIndexPath = [mainTable indexPathForRowAtPoint:touchPoint];
NSLog(@"index path.section ==%ld",(long)clickedButtonIndexPath.section);
NSLog(@"index path.row ==%ld",(long)clickedButtonIndexPath.row);
}
Swift3
func addItem(sender: UIButton)
{
var touchPoint = sender.convert(CGPoint.zero, to: self.maintable)
// maintable --> replace your tableview name
var clickedButtonIndexPath = maintable.indexPathForRow(at: touchPoint)
NSLog("index path.section ==%ld", Int(clickedButtonIndexPath.section))
NSLog("index path.row ==%ld", Int(clickedButtonIndexPath.row))
}
Swift2 and above
func addItem(sender: UIButton)
{
var touchPoint: CGPoint = sender.convertPoint(CGPointZero, toView: mainTable)
// maintable --> replace your tableview name
var clickedButtonIndexPath: NSIndexPath = mainTable(forRowAtPoint: touchPoint)
NSLog("index path.section ==%ld", Int(clickedButtonIndexPath.section))
NSLog("index path.row ==%ld", Int(clickedButtonIndexPath.row))
}
Swift 3
let clickedButtonIndexPath = self.tableView.indexPathForRow(at: touchPoint)
if(clickedButtonIndexPath != nil)
{
NSLog("index path.section ==%ld", Int(clickedButtonIndexPath!.section))
NSLog("index path.row ==%ld", Int(clickedButtonIndexPath!.row))
}