user4950087
user4950087

Reputation: 21

Multiple child table view controller in UIViewController swift

I am a newbie Swift developer. I would like to receive some advice from experts on how to solve the following problem I am facing.

I am trying to embed in a UIViewController two child views controller and display both of them at the same time in the UIViewController, that is the parent view controller.

These two child view controllers are both UITableViewControllers: the first one is a table view with two sections and 3 rows per each section, the second child view is also a table but it displays some data dynamically.

Using the code below I managed to load and display each UITableViewController successfully but I can't display them both at the same time one below the other. Is there a way I can solve my problem?

Thank you so muck for your patience and kindness.

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let firstTable = storyboard.instantiateViewControllerWithIdentifier("FirstTable") as! UINavigationController
        let thirdTable = storyboard.instantiateViewControllerWithIdentifier("ThirdTable") as! UINavigationController

        self.addChildViewController(firstTable)
        firstTable.view.frame = self.view.bounds
        self.view.addSubview(firstTable.view)
        firstTable.didMoveToParentViewController(self)

        self.addChildViewController(thirdTable)
        thirdTable.view.frame = self.view.bounds
        self.view.addSubview(thirdTable.view)
        thirdTable.didMoveToParentViewController(self)
    }
}

Upvotes: 0

Views: 2081

Answers (2)

Icaro
Icaro

Reputation: 14845

You can easily add container in the storyboard, this container can be connect to any view controller using control drag and selection embedded

enter image description here

I hope that helps you!

Upvotes: 2

AlBirdie
AlBirdie

Reputation: 2071

In order to show multiple UIViewControllers on the same UIViewController, Apple recommends using Container Views (https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/CreatingCustomContainerViewControllers/CreatingCustomContainerViewControllers.html). In essence, they function as the child UIViewController's view target. That way you can have multiple UIViewController views on a single UIViewController.

However, are you sure you need two separate controllers for your table views? If you can get away with a single controller for two tableviews, I'd recommend using a UIViewController instead of UITableViewController, add two UITableViews manually and add the required datasource and delegate methods to your UIViewController.

Upvotes: 1

Related Questions