FrozenHeart
FrozenHeart

Reputation: 20766

How to detect button on which cell was exactly selected

Suppose that I have a custom UITableViewCell contains UIButton control. When the user presses the button it should present another view controller with the appropriate info according to which cell was chosen (to be more precise, I have an array of objects used to represent information in the UITableView and I want to transfer this info to the next view controller). The question is how can I detect button on which cell was exactly selected?

Thanks in advance.

Upvotes: 0

Views: 87

Answers (3)

Mayank Jain
Mayank Jain

Reputation: 5754

There are many ways of doing this.. but the way of superView is no more available since iOS8. I am sharing a code which is working perfect in all iOS.

Write this selector on your cellForRow method

[cell.btnOnCell addTarget:self action:@selector(btnAction:event:) forControlEvents:UIControlEventTouchUpInside];

Now write this method

-(void)btnAction: (UIButton *)sender event:(id)event
{
    NSSet *touches = [event allTouches];
    UITouch *touch = [touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:self.tblView];
    NSIndexPath *indexPath = [self.tblView indexPathForRowAtPoint:currentTouchPosition];
    NSLog(@"%li",(long)indexPath.row);
}

Upvotes: 3

Pandey_Laxman
Pandey_Laxman

Reputation: 3918

Simple solution is that when you configure cell in CellForRowAtIndexPath there you need to set the cell.button.tag=100+indexPath.row.

-(void)btnClicked:(UIButton *)sender
{
NSIndexPath* path= [NSIndexPath indexPathForRow:sender.tag-100 inSection:0];
UITableViewCell*cell=(UITableViewCell *)[tblView cellForRowAtIndexPath:path];
}

NOTE: you need to remove addTarget and buttonClicked implementation from UITableviewcell and in cellForRowAtIndexPath method addtarget to button and in this class implemnt buttonClicked Method.**

Upvotes: 0

Balaji Kondalrayal
Balaji Kondalrayal

Reputation: 1751

Try this:

Insert below code in cellForRowAtIndexpath

[cell.yourbuttonName addTarget:self action:@selector(yourbuttonNamePressed:) forControlEvents:UIControlEventTouchDown];

paste the below code as separate method

- (void)yourbuttonNamePressed:(UIButton *)sender
{
CGPoint swipepoint = sender.center;
CGPoint rootViewPoint = [sender.superview convertPoint:swipepoint toView:self.goalsTable];
NSIndexPath *indexPath = [self.goalsTable indexPathForRowAtPoint:rootViewPoint];
}

Upvotes: 0

Related Questions