Question

I am trying to show a UIViewController on top of other UIViewcontroller using addChildViewController functionality.The childViewController is a tableView which shows up on top of my MainViewController however I do not see the table view that it has.If I execute the childViewController separately , the tableView works fine , so what am I missing here.

Here's how I am adding a childVC:

     @implementation Test2ViewController

   - (void)viewDidLoad
  {
     [super viewDidLoad];
  }

 - (IBAction)showChildVC:(id)sender
 {
   TestTableViewController *tVC = [[TestTableViewController alloc]init];
   tVC.view.frame = CGRectMake(50, 50, 200, 200);
   [self addChildViewController:tVC];
   [self.view addSubview:tVC.view];
   [tVC didMoveToParentViewController:self];
 }

And this is the childVC that I want to show: .h

     #import <UIKit/UIKit.h>

     @interface TestTableViewController : UIViewController<UITableViewDataSource>
     {
        NSArray *array;
     }
       @property (weak, nonatomic) IBOutlet UITableView *tableView;

      @end

And: .m

     - (void)viewDidLoad
     {
       [super viewDidLoad];
       self.view.backgroundColor = [UIColor grayColor];
   array = [NSArray arrayWithObjects:@"One",@"Two",@"Three",@"Four", nil];

      }

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        return [array count];
    }
     - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
     {
         static NSString *cellIdentifier = @"Cell";
         UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
         if (cell == nil) {
         cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }

         cell.textLabel.text = [array objectAtIndex:indexPath.row];
         return cell;

       }
Was it helpful?

Solution

I see your table view in the second view controller is an IBOutlet, so you are placing it in Storyboard.

Then when you instantiate it, you can't do: [[TestTableViewController alloc]init]; you have to do:

[storyBoard instantiateViewControllerWithIdentifier:@"tVCStoryBoardID"];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top