I need to display UITableViewController programmatically from existing view.
I have a MyAppViewController and the button on its view should open a new UITableViewController. But I cannot seem to get it working so far. Here is how UITableViewController looks like:
@interface SecondViewController : UITableViewController{}
and on the main view I add table view controller using the following:
SecondViewController vc2 = [[SecondViewController alloc] init];
vc2.view.frame = {...}
[self.view addSubview: vc2.view];
This is how I would normally add a simple view controller so I thought UITableViewController is the same.
The result I get is empty cells on the entire screen. This is because of the delegate not set, I assume, but where would I set it? So my confusion is the delegate setters on UITableViewController view controller and displaying UITableViewController correctly from the main view controller’s view.
EDIT
This answer is outdated. The correct way to add a view controller’s view as a subview of another view controller is to implement a container view controller.
https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/CreatingCustomContainerViewControllers/CreatingCustomContainerViewControllers.html
ORIGINAL ANSWER
Your pattern is a bit out of the ordinary. The most common way to do what you are describing is to initialize and present SecondViewController. If that’s in fact what you want I highly recommend you peruse Apple’s docs on how to create, customize, and present
UIViewControllerandUITableViewController.If you know all of that and really want to do something custom then read on.
Instead you are creating an instance of SecondViewController and rather than presenting it, you are adding it’s view to the current view controllers view. If you know what you’re trying to accomplish and this is in fact your desired result then go for it.
There is more than one way to configure this general pattern. I’ll stick to the simplest way in this example.
1)
MainViewController(MVC) should retain theSecondViewController(SVC) instance in a property as long as it is needed.2) SVC is a subclass of
UITableViewControllerso by default, it is set as thedataSourceanddelegatefor it’sUITableView. That means you need to implement theUITableViewDataSourceandUITableViewDelegatemethods inSVCfor your table to be populated with data. AssumingMVCknows what data needs to go into the table, it should pass this toSVC. The simplest way is to define a property onSVCthat can be set inMVCat initialization time.3) Assuming there is a way to dismiss the table after it has been presented, you’ll want
MVCto do that. Basically,MVCwould removeSVC‘s view from it’s superview and then set theSVCproperty to nil.Here’s some quick psuedo-code. I wrote the bare minimum as an example.