Teo
Teo

Reputation: 3442

iOS get specific UITableViewCell

I have a UIButton in a custom UITableViewCell. This button triggers an event when clicked.

[myButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; 

The method which is called when the button is clicked is :

 - (void) buttonClicked:(id)sender
{

UIButton *b = (UIButton*)sender;

.....

} 

My question is, how can I get an instance of the cell in which the button is placed?

Upvotes: 1

Views: 406

Answers (5)

matt
matt

Reputation: 536046

As you rightly say, the button is "in" the cell - in the sense that it is a subview, at some depth, of some cell. So simply walk up the view hierarchy until you reach the cell:

- (void) buttonClicked:(id)sender {
    UIView* v = sender;
    while (![v isKindOfClass:[UITableViewCell class]])
        v = v.superview;
    // now v is the cell
}

Upvotes: 0

indu
indu

Reputation: 323

 UITableViewCell *cell = (UITableViewCell*)[[b superview] superview];

If you added the button on cell as subview then superview of button will be contentView and superview of contentView will UITableViewCell

Upvotes: 2

eagle.dan.1349
eagle.dan.1349

Reputation: 631

I'd suggest you not just to put a button into a UITableViewCell. What you should better to is to subclass UITableViewCell and make UITableViewButtonCell that will cal a delegate callback like this: - (void) tableViewButtonCellDidButtonTap:(UITableViewCell*) buttonCell This will be more SOLID solution.

The case with UIButton *b = (UIButton*)sender;
UITableViewCell *tableViewCell =(UITableViewCell*) [b superview];
will only work if your button lies DIRECTLY insade the UITableviewCell that can possibly be not a case.

Upvotes: 0

Shamsudheen TK
Shamsudheen TK

Reputation: 31311

- (void) buttonClicked:(id)sender
{


  UIButton *b = (UIButton*)sender;    
  UITableViewCell *tableViewCell =(UITableViewCell*) [b superview];  

 //if you added the UIButton as a subview of UITableViewCell contendView, use this
  UITableViewCell *tableViewCell =(UITableViewCell*) [[b superview] superview]; 

} 

Upvotes: 0

Susim Samanta
Susim Samanta

Reputation: 1593

You can set tag to button when you are adding the buttons in table view cell. It will be better if you use same indexPath of able view cell. Then from [sender tag] you able to get the indexPath value.

Upvotes: 0

Related Questions