Search code examples
iosswiftaddsubview

Add TableViewController as SubView


With may App I have 2 TableViewControllers Inbox and Outbox(each with its own custom cells) and Main ViewController Mail with a segment controller and UIView beneath it, what Im trying is to add the tableview controllers and switch between them on segment controller is pushed but its not working at all!

Mail ViewController :

import UIKit

class Mail: UIViewController, SegmentControllerDelegate {

    func indexChanged(index: Int) {
        print("index\(index)")
        switch index {
        case 0:
            container.bringSubviewToFront(inbox)
            break
            case 1:
            container.bringSubviewToFront(outbox)
            break
        default:
            break
        }
    }
var inbox: UIView!
    var outbox : UIView!
    override func viewDidLoad() {
        super.viewDidLoad()

        inbox = storyboard?.instantiateViewController(withIdentifier: "inbox").view
        outbox = Outbox().view
        container.addSubview(inbox)
        container.addSubview(outbox)


    }

    override func viewDidLayoutSubviews() {
        inbox.frame = container.bounds
        outbox.frame = container.bounds


    }

And this is the result while my Inbox and Outbox tableview is filled with data

enter image description here

Any help will be much appreciated


Solution

  • All you are currently doing is getting the view from the other controllers. You need to create an instance of the view controllers and keep them in memory.

    This can be done by adding them as child view controllers:

        // for both inbox and outbox table view controllers,
        //  instantiate
        //  add as child view controller
        //  add its view as a subview of container
        //  finish with .didMove()
    
        inboxTVC = InboxTableViewController()
        addChild(inboxTVC)
        container.addSubview(inboxTVC.view)
        inboxTVC.didMove(toParent: self)
    
        outboxTVC = OutboxTableViewController()
        addChild(outboxTVC)
        container.addSubview(outboxTVC.view)
        outboxTVC.didMove(toParent: self)
    

    I've updated the project I put together for your other question with this implemented: https://github.com/DonMag/AliAdil