开发者

UIButton on Custom UITableViewCell

开发者 https://www.devze.com 2023-02-13 22:45 出处:网络
I have a Custom UITableViewCell that has a couple buttons. When the code was all under on开发者_如何学运维e view controller, my button was declared like this:

I have a Custom UITableViewCell that has a couple buttons. When the code was all under on开发者_如何学运维e 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.


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];


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

0

精彩评论

暂无评论...
验证码 换一张
取 消