简体   繁体   中英

How in Objective-C to reference parent UIViewController from prototype cell?

I have a slide menu. It is implemented using component SWRevealViewController . To implement it I have 1 main UIViewController ( VC ) - SWRevealViewController . I have menu VC and I have push segues to navigate to different menu's VCs .

For the menu I use prototype cells with custom class for each menu.

My problem is that I need to call unwind segue to go to login VC , using alert view . To do that I try usual method [self performSegueWithIdentifier:@"unwSegReturnToLogin" sender:self]; on positive answer from the alert view (inside custom class for exit cell). I have such method declared in my login VC . I receive error during the compilation:

No visible @interface for 'tvcellExitMenuItem' declares 
the selector 'performSegueWithIdentifier:sender:'

I suspect that the problem is that self in my case is table cell and that is not UIViewController .

How to refer parent VC if this is the case?

If not, please tell me where I am wrong in the logic.

A subview shouldn't have to know about its parent viewController. Instead, a common pattern that fits your need is the delegate pattern : define a delegate property & protocol for your cells' class.

// your cell class header might look like this

@class MyCellClass;
@protocol MyCellDelegate

- (void)onCellSelected:(MyCellClass *)cell;

@end

@interface MyCellClass

@property (nonatomic, weak) id<MyCellDelegate> delegate;

@end

For example, if your viewController is also your UITableViewDatasource , then in tableView:cellForRowAtIndexPath: you can set your cell's delegate to self , and call the segue methods in delegate method.

- (void)onCellSelected:(MyCellClass *)cell
{
    // retrieve cell indexPath
    NSIndexPath *cellIndexPath = [self.tableView indexPathForCell:cell];

   // using indexPth, retrieve cell's data

   // push segue with data selected
}

Of course, this is only an example, and there are other corrects ways to do that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM