1
votes

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.

2
maybe it's just me but the code for the button looks exactly the same.Matthias Bauch
Maybe your code isn't really like that, but you're not adding the same button you're creating (myButton vs damageButton).jv42
@fluchtpunkt - The only difference is the target is a view controller I'm passing as a propertyDVG
@jv42 was renaming things to make it generic, missed that one.DVG

2 Answers

6
votes

The problem, in the end, was that I was adding the subview to the cell object and not the contentview of the cell object. I changed the button code to this and it was resolved:

UIButton *button = (UIButton *)sender;
UITableViewCell *cell = (UITableViewCell *)[button superview];
NSIndexPath *indexPath = [[self tableView] indexPathForCell:cell];
-1
votes

Don't subclass UITableViewCell (or UITableView), it's usually unnecessary and can cause problems. Table cells have a contentView which is a great place for customization.

Recommended reading:

http://cocoawithlove.com/2009/04/easy-custom-uitableview-drawing.html

and then:

http://cocoawithlove.com/2010/12/uitableview-construction-drawing-and.html