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
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
}
...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With