Sam
Sam

Reputation: 526

How to hide container view from another view controller Swift

Here's the screenshot of Main.storyboard.

enter image description here

I'm trying to hide-unhide the audioBarView(container view of StartingViewController) depending on the view controller. On the screenshot, I presented where is necessary that view and where not.

I've tried to create an instance of StartingViewController in BrowserVC or anywhere else but it triggers an error(audioBarView = nil).

If you need more information please respond.

Upvotes: 1

Views: 708

Answers (2)

Dima G
Dima G

Reputation: 2025

While NotificationCenter is great for decoupling, sometimes you can also consider callbacks for parent-child communication. E.g. "Now Playing Music" is a child of "Starting View Controller".

You can use :

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get child view controller(s) using segue.destination and keep a reference to it.
    // provide callback handler for some event

    // in the callback handler, you can directly invoke any function in a relevant child ViewController via reference.
}

Upvotes: 0

Muhammad Zeeshan
Muhammad Zeeshan

Reputation: 2451

You can use NotificationCenter to fire an event from your desired view controller that can contains the additional information i.e. show/hide container view.

In your StartingViewController you can define a function that will be responsible to show/hide container view. In the viewDidLoad you can add an observer like:

NotificationCenter.default.addObserver(self, selector: #selector(playerVisibilityNeedsChangeNotification(notif:)), name: Notification.Name(rawValue: "PlayerVisibilityNeedsToBeUpdate"), object: nil)

Define event handler function in your StartingViewController

func changePlayerVisibility(show: Bool) {
    self.playerContainerView.isHidden = !show
}

@objc func playerVisibilityNeedsChangeNotification(notif: Notification) {
    let show = notif.object as? Bool ?? false
    self.changePlayerVisibility(show: show)
} 

Post the notification from your desired view controller:

let show = false
NotificationCenter.default.post(name: Notification.Name(rawValue: "PlayerVisibilityNeedsToBeUpdate"), object: show)

Upvotes: 3

Related Questions