views:

531

answers:

4

Hi.

I have a pretty big issue. I am trying to create a favorite-button on every UITableViewCell in a UITableView. That works very good, and I currently have an action and selector performed when pressed.

accessory = [UIButton buttonWithType:UIButtonTypeCustom];
[accessory setImage:[UIImage imageNamed:@"star.png"] forState:UIControlStateNormal];
accessory.frame = CGRectMake(0, 0, 15, 15);
accessory.userInteractionEnabled = YES;
[accessory addTarget:self action:@selector(didTapStar) forControlEvents:UIControlEventTouchUpInside];
cell.accessoryView = accessory;

And selector:

- (void) didTapStar {
 UITableViewCell *newCell = [tableView cellForRowAtIndexPath:???];

 accessory = [UIButton buttonWithType:UIButtonTypeCustom];
 [accessory setImage:[UIImage imageNamed:@"stared.png"] forState:UIControlStateNormal];
 accessory.frame = CGRectMake(0, 0, 26, 26);
 accessory.userInteractionEnabled = YES;
 [accessory addTarget:self action:@selector(didTapStar) forControlEvents:UIControlEventTouchDown];
 newCell.accessoryView = accessory;
}

Now, here's the problem: I want to know what row the accessory that was pressed belongs to. How can I do this?

Thank you :)

+1  A: 

Change your action around a bit.

- (void)action:(id)sender forEvent:(UIEvent *)event

Inside that method:

NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:[[[event touchesForView:sender] anyObject] locationInView:tableView]];

That should get you the row's index path.

Giao
Thank you so much - that works perfectly! Thank you! :)
Emil
A: 

I would use the following code:

  • (void)didTapStar:(id)sender { NSIndexPath *indexPath = [tableView indexPathForCell:(UITableViewCell *)[sender superview]]; }
Bas Dirkse
A: 

That returns (in my case) row 0 by tapping at every row.

The code Giao posted, works! Thanks!

Wubbe
Please add comments in comment-boxes :)
Emil
A: 

I want to change my UITablecellaccessorycheckmark into a button.i means when table view load it shows accessory and when i click on accessory it turns into button with some title and have some functionality

Sahil Goenka
Make a new question instead of asking here. You won't get answered.
Emil