// // HomeVC.swift // WOKA // // Created by Bilal on 24/05/2024. // import UIKit protocol ChildViewControllerDelegate: AnyObject { func didPressSwitchButton(from viewController: UIViewController) } class HomeVC: UIViewController ,ChildViewControllerDelegate{ @IBOutlet weak var containerView: UIView! var currentChildViewController: UIViewController? override func viewDidLoad() { super.viewDidLoad() // Initialize the first child view controller let sb = UIStoryboard(name: "Theme", bundle: nil) if let firstVC = sb.instantiateViewController(withIdentifier: "ThemeOneVC") as? ThemeOneVC { add(asChildViewController: firstVC) firstVC.delegate = self } } func didPressSwitchButton(from viewController: UIViewController) { if viewController is ThemeOneVC { switchToViewController(withIdentifier: "ThemeTwoVC") } else if viewController is ThemeTwoVC { switchToViewController(withIdentifier: "ThemeOneVC") } } private func switchToViewController(withIdentifier identifier: String) { let sb = UIStoryboard(name: "Theme", bundle: nil) let newVC = sb.instantiateViewController(withIdentifier: identifier) if let newVC = newVC as? ThemeOneVC { newVC.delegate = self } else if let newVC = newVC as? ThemeTwoVC { newVC.delegate = self } print("Switching to view controller with identifier \(identifier)") replaceCurrentChildViewController(with: newVC) } private func add(asChildViewController viewController: UIViewController) { print("Adding child view controller: \(viewController)") addChild(viewController) viewController.view.frame = containerView.bounds containerView.addSubview(viewController.view) viewController.didMove(toParent: self) currentChildViewController = viewController } private func remove(asChildViewController viewController: UIViewController) { print("Removing child view controller: \(viewController)") viewController.willMove(toParent: nil) viewController.view.removeFromSuperview() viewController.removeFromParent() } private func replaceCurrentChildViewController(with newViewController: UIViewController) { // Clear previous views containerView.subviews.forEach { $0.removeFromSuperview() } // Remove current child view controller if exists if let currentVC = currentChildViewController { remove(asChildViewController: currentVC) } // Add new child view controller add(asChildViewController: newViewController) } }