1

I have a UIViewController in my storyboard. Inside this UIViewController, I have a container which embed with a tableViewController. This tableViewController is a static table. How can I use this tableViewController inside UIViewController?

I have set protocols like UITableViewDelegate, UITableViewDataSource and I have no idea how I can get that tableViewController and delegate to my UIViewController.

Below are the screen.

P.S. I was trying to make a side navigation bar. Please notify me if you need to see any code.

enter image description here

Johnny Cheuk
  • 237
  • 2
  • 15
  • you can use UIViewController as parent ViewController and tableViewController as childViewController. But better solution is to use UITableView in UIViewController as a subView. – Sandeep Kumar Mar 30 '16 at 02:58
  • Since it is a static table, I cannot put it in the UIViewController. There will be error when I build it. That's why I'm putting a container view inside the UIViewController and embed with a tableViewController. It seems like the parent ViewController way will work. But can you tell me more about it? – Johnny Cheuk Mar 30 '16 at 03:00
  • @SandeepKumar Thanks Kumar it works like a charm! – Johnny Cheuk Mar 30 '16 at 03:07

3 Answers3

1

This is my opinion: create a delegate for your tableViewController like

@protocol SideTableViewContollerDelegate <NSObject>

- (void)didClickCellOfIndexPath:(NSIndexPath *)indexPath;

@end

@interface SideTableViewController

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

@end

and inside your UIViewController, you set the controller as the tableViewController's delegate

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([segue.identifier isEqualToString:@"go table view"]) {
       SideTableViewController *stvc = (SideTableViewController *)segue.destinationViewController;
       stvc.delegate = self;
   }
}

and inside the tableView's delegate function "didSelectRowAtIndexPath" do:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   [self.delegate didClickCellOfIndexPath:indexPath];
   [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

and all that left is implementing tableView controller's delegate in the uiview controller

MudOnTire
  • 506
  • 3
  • 9
0

Turns out I have to set the class in the embed tableViewController and put the [self addChildViewController: myTableViewController] in the UIViewController class. And I can implement in the UITableViewController class to control it.

Johnny Cheuk
  • 237
  • 2
  • 15
0

You can use segue to access the tableViewController. Just implement - (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender and it will be called before viewController's viewDidLoad. See this answer: Access Container View Controller from Parent iOS

Community
  • 1
  • 1
Bing
  • 351
  • 3
  • 12