Reputation: 8214
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
Upvotes: 7
Views: 4158
Reputation: 126507
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.
Upvotes: 2
Reputation: 4513
I've done something very similar that gets the table reference from a custom cell using a button event.
Code:
-(IBAction)onShareTap:(UIButton *)sender { // i've used a button as input..
UIButton *senderButton = (UIButton *)sender;
UITableViewCell *buttonCell = (UITableViewCell *)senderButton.superview.superview.superview;
UITableView* table = (UITableView *)[buttonCell superview];
NSLog(@"Table: %@", table);
}
Upvotes: -1
Reputation: 10182
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
}
...
Upvotes: 4