简体   繁体   中英

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)
    }
}

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

在此处输入图片说明

I hope that helps you!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM