I have a Custom UITableViewCell that has a couple buttons. When the code was all under one view controller, my button was declared like this:
myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[myButton addTarget:self
action:@selector(myButtonAction:)
forControlEvents:UIControlEventTouchUpInside];
[myButton setTitle:@"Action" forState:UIControlStateNormal];
myButton.frame = CGRectMake(20, 80, 72, 37);
[self addSubview:myButton];
Last night I subclassed UITableViewCell, so the code became this:
myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[myButton addTarget:viewController
action:@selector(myButtonAction:)
forControlEvents:UIControlEventTouchUpInside];
[myButton setTitle:@"Action" forState:UIControlStateNormal];
myButton.frame = CGRectMake(20, 80, 72, 37);
[self addSubview:damageButton];
Since doing this, however, pushing the button on any cell causes the action to only effect the first row in the table, and I'm not sure why.
Action code:
UIButton *button = (UIButton *)sender;
UIView *contentView = [button superview];
UITableViewCell *cell = (UITableViewCell *)[contentView superview];
NSIndexPath *indexPath = [[self tableView] indexPathForCell:cell];
//do something with objectAtIndex:indexPath.row
I understand it's common to set the Tag Property to indexPath.row for using a UIButton in a table view. However, I'm using two separate arrays in the data source to populate two different sections of the TableView, so I don't think that will work.