Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subview a UITableViewController within another Controller using Storyboards

I have encapsulated all my table view logic on a UITableViewController that is linked to a view. This was done using storyboards.

I would like to embed this logic and view within another view controller / view (kind of like a header information with a scrollable table beneath.)

I have the following components: CustomViewController which is linked to a UIView (dragged in from storyboard) CustomTableViewController which is linked to a UITableView (dragged in from storyboard)

Essentially I am trying to mimic the scenario of the Stopwatch in the iOS clock app

  • What is the beast approach to this?
  • How is it done programatically?
  • Can this be done on the storyboard somehow?

Any help would be greatly appreciated. Thanks

like image 731
Slappy Avatar asked Apr 15 '12 04:04

Slappy


1 Answers

Ok figured it out. This solution is iOS 5 specific since this feature was added there. This method works with storyboards.

Setup: The intention is to host one view controllers view and logic within another controller.

  1. Since there is no intrinsic way to reference the child view controller in the storyboard, we need to give the view controller a name. This can be done by filling out the "Identifier" attribute on the controller in the storyboard. NOTE: Make sure you are giving the controller the identifier and not the controllers view.

  2. Instantiate the controller you want to aggregate. This can be done from the hosting controller.

    UIViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:@"ControllerIdentifier"];
    
  3. Add the child controller to the parent controller

    [self addChildViewController: controller];
    
  4. Add the child controllers view to the parent controllers view. Note if you have a place holder view in the parent controller you wish to add the child view to, then this is where you do it. Here I add it the a UIView called stage in the parent controller.

    [self clearStage]; 
    [self.stageView addSubview:controller.view];
    presentedController.view.frame = self.stageView.bounds;
    

And that is it. Pretty simple. I have used it successfully with switching controllers and view in a home made tab control. The sub controller enlists its views in the view lifecycle, so the viewDidLoad, etc all work as expected in this child view controller.

Hopes this helps someone.

like image 196
Slappy Avatar answered Nov 20 '22 02:11

Slappy