ExBen ExBen - 1 year ago 103
iOS Question

set action for UIButton in customized UITableViewCell which has many other views

I read below posts:

How to set Action for UIButton in UITableViewCell

Add an action to a custom UITableViewCell

But all the solutions do not work for me. I am not sure what I missed;
I have a customized

which lives in a xib file, this cell contains a
, one
. I hope to when user click the UIButton, it will delete current item from the list, when user select the row, it will navigate to another page.

What I done : From the asked question above, I create a
and addTarget,then add the button into cell with
[cell.contentview addsubview:button]
, the button action can be triggered.

There are some other views, I hope to layout them in xib, then do not need layout with code.

So I create a button in the xib, and call setTarget for this button (outlet in my customized cell class), the button action can not be triggered.

Then I add a
in the xib as placeholder, and create a new button with code and add the button into the placeholder
, button action can not be triggered.

So it seems the way to make it work must be:

  1. Create a button with code;

  2. Add target, then add this button into cell's content view directly;

It seems pretty annoying since I don't want to layout views with code. Do I miss something?

Answer Source

First add one button in the contentView of UITableViewCell in the xib file and create the outlet in customCell. After that change your code of cellForRowAtIndex like this.

[cell.btn addTarget:self action:@selector(btnTap:) forControlEvents:UIControlEventTouchUpInside];

After that create this btnTap method

- (void)btnTap:(UIButton*)sender {
     CustomCell *cell = (CustomCell*) [[sender superview] superview]; //If you have button inside another view you need to add superView on your hierarchy basis.
     NSIndexPath *indexPath = [self.tblFile indexPathForCell:cell];
     NSLog(@"Row you want to delete - %d",indexPath.row);

Hope this will help you.