Kapil Rathore
Kapil Rathore

Reputation: 82

Sharing common view between different tabs in UITabBarController

I want to create a common view which is shared by all the child viewControllers of a UITabBarController.

I tried to achieve this by container view but that creates different instances for each child viewControllers.

Thanks!

Upvotes: 1

Views: 669

Answers (1)

ezaji
ezaji

Reputation: 304

Unfortunately, there is no way to share view between two different superviews or two different view controllers (each view controller has root view).

https://developer.apple.com/documentation/uikit/uiview/1622616-addsubview

Views can have only one superview. If view already has a superview and that view is not the receiver, this method removes the previous superview before making the receiver its new superview.

But you can simulate the same behaviour by making shared data model that contains appropriate properties to display identical view on different view controllers.

struct ViewModel {
    let frame: CGRect
    let backgroundColor: UIColor
    // other properties that identify view state 
}

class FirstViewController: UIViewController {
    var model: ViewModel?

    @IBOutlet weak var customView: UIView! // view that you want to customize from ViewModel. You can create it programmatically.

    override func viewDidLoad() {
        super.viewDidLoad()

        guard let viewModel = model else { return }

        customView.frame = viewModel.frame
        customView.backgroundColor = viewModel.backgroundColor
    }
}

class SecondViewController: UIViewController {
    var model: ViewModel?

    @IBOutlet weak var customView: UIView! // view that you want to customize from ViewModel. You can create it programmatically.

    override func viewDidLoad() {
        super.viewDidLoad()

        guard let viewModel = model else { return }

        customView.frame = viewModel.frame
        customView.backgroundColor = viewModel.backgroundColor
    }
}

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
        // Hierarchy of view controllers is created by storyboard (UITabBarController contains FirstViewController & SecondViewController)
        let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)

        let tabBarController = mainStoryboard.instantiateInitialViewController() as! UITabBarController

        let viewModel = ViewModel(frame: CGRect(x: 10, y: 10, width: 20, height: 20), backgroundColor: UIColor.cyan)
        (tabBarController.viewControllers[0] as! FirstViewController).model = viewModel
        (tabBarController.viewControllers[1] as! SecondViewController).model = viewModel

        window = UIWindow(frame: UIScreen.main.bounds)
        window.rootViewController = tabBarController 

        return true
    }
}

Upvotes: 2

Related Questions