Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a reference to Table View Controller from Custom Table View Cell class

I have custom table view cell and have made a custom class. How can I get reference to the table view controller from the cell?

I have this custom tableview cell class. In this I have a button which is connected with a tap event. On tap I get the event fine but I am looking to get a hold on the table view controller so I can show the action sheet on top of the table view.

@interface MTPurchasedCartItemCell : UITableViewCell

- (IBAction)onShareTap:(id)sender;

@end
like image 250
Encore PTL Avatar asked Aug 28 '13 22:08

Encore PTL


2 Answers

The way I would do this would be to use a block event handler. In your MTPurchasedCartItemCell class add a property in the header file like so:

@property (nonatomic, copy) void (^tapHandler)(id sender);

And in the implementation file you can do this:

- (IBAction)onShareTap:(id)sender {
    if (self.tapHandler) {
        tapHandler(sender);
    }
}

And finally in your controller class, do something like this in your cellForRowAtIndexPath::

...
cell.tapHandler = ^(id sender) {
    // do something
}
...
like image 156
edc1591 Avatar answered Nov 11 '22 03:11

edc1591


You might also consider adding a public @property for the button to the custom cell.

To do that, add the following line to the header file of your custom cell class:

@property (weak, nonatomic) IBOutlet UIButton *myButton;

That's if you're creating the button in Interface Builder. If you're creating the button in code, you'd add this line instead:

@property (nonatomic) UIButton *myButton;

Then, when initializing or configuring the cell from your table view controller, you now have a reference to myButton and can add an action to it with your table view controller as the target.

Then, in the action method, you can get the cell from the button. The answer to Objective-C: How to generate one unique NSInteger from two NSIntegers? explains how.

like image 20
ma11hew28 Avatar answered Nov 11 '22 02:11

ma11hew28