Search code examples
uitableviewviewcontrollerpushviewcontroller

Push a view controller from table embedded in a UIScrollView


The structure for my view is as follows. I display the cover of each chapter of a catalogue in the header view of a UITableView, and display the subsections of each chapter in the corresponding table view.I have these all embedded in a paging UIScrollView which is the rootViewController for a navigation controller. The stack is:

UINavigationController (controlled by CatMainViewController [UIViewController])
    UIScrollView       (controlled by CatMainViewController [UIViewController])
        UITableView    (controlled by SectionViewController [UITableViewController])

I would like to know how I can communicate with the CatMainViewController from the didSelectRowAtIndexPath method on my SectionViewController to tell the navigation controller to push a view controller which loads a document.

I have tried something like:

#import "CatMainViewController.m"
[CatMainViewController.self.navigationController pushViewController:newView animated:YES];

But obviously this hasn't worked out so well. Any help would be greatly appreciated! Thanks.


Solution

  • You can pass a reference of the CatMainViewController instance to the SectionViewController instance, for example:

    /* SectionViewController.h */
    @class CatMainViewController;
    
    @interface SectionViewController
    
    // ... some properties/methods
    @property (nonatomic, assign) CatMainViewController *catMainVC;
    // ... more properties/methods
    
    @end
    
    /* SectionViewController.m */
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        // ... some code
        [self.catMainVC.navigationController pushViewController:someVC animated:YES];
    }
    
    /* CatMainViewController.m */
    #import "SectionViewController.h"
    
    // when creating the SectionViewController
    SectionViewController *sectionViewController = ...;
    sectionViewController.catMainVC = self;
    

    This is similar to the delegate/@protocol scheme that Apple uses.