UIButton inside UITableViewController
I have a开发者_开发问答 UIButton
that is created inside of each table cell. I want to hook up a touch event like so:
[imageButton addTarget:self
action:@selector(startVote:)
forControlEvents:UIControlEventTouchUpInside];
I want to pass data about the current row (the id of the object for that row) to the startVote method. Is there a method that I am missing to do this or am I breaking some best practice. This seems like a very normal thing to do?
I assume you have some sort of NSArray
with the data that gets passed on to the buttons in cellForRowAtIndexPath
.
Try this in startVote
:
- (void)startVote:(id)sender {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
NSDictionary *myData = [myArray objectAtIndex:indexPath.row];
}
EDIT:
If for some reason the row is not selected, you can assign a unique tag
to every button upon creation and then:
- (void)startVote:(id)sender {
int myTag = [(UIButton *)sender tag];
NSDictionary *myData = [myArray objectAtIndex:myTag];
}
Maybe you would do some sort of operation with the tag
so it can be used as an index (I add a certain amount to every tag
so it will not conflict with "automatic" tagging used by the OS.
The UITableViewCell
doesn't know, out of the box, what row it's displaying in the table. Remember, the intent is that the same cell instances are re-used all over the table to display its data. That said, your UITableViewController
is responsible for setting up the cells and passing them to the system (and has the index path, of course). You could, at that point, do something like:
- Assuming it's a custom cell class, set a property on the cell instance to identify what row it's displaying, and which your button can later use.
- If you're putting these buttons in the cells as their accessory views, take a look at the table delegate's
tableView:accessoryButtonTappedForRowWithIndexPath:
method. - If it's a one-section table, you could do something really cheesy like store the row index in the button's
tag
property. YourstartVote:
method is passed the button, and could then extract its tag.
精彩评论