Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call parent View controller function from container view

Tags:

ios

swift

I have a container view which performs a couple of segues inside based upon a users actions. I also have a top UIView that I would like to control from within the container view segue and set it's state.

I've tried to set a delegate to the home controller using a protocol and also the following approach:

 if let parent = self.parent as? HomeController { 
        parent.handleTopBarState(state: .web)
 }

What I would like to happen is when I'm on a specific view controller, set the parent view controller's top bar view's state.

Thanks.

like image 326
user7684436 Avatar asked Mar 10 '17 12:03

user7684436


2 Answers

If you have added child view controller then you can access simply with self.parent. To make sure put it in if let and cast

if let parent = self.parent as? ParentViewController {
        parent.resetItemsCollectionView()
    }
like image 145
Ammar Mujeeb Avatar answered Nov 14 '22 02:11

Ammar Mujeeb


If you have embedded view controller on another view controller, you can message it's parent view controller with many ways.

  1. In child (embedded) view controller, you can have reference to parent. Give identifier to the embedding segue in the storyboard, declare var with type of the parent in child, and assign the parent on prepare(for segue: UIStoryboardSegue, sender: Any?) function, and call any public methods of the parent.
  2. Create protocol, make the parent confirm to the protocol, create var of the protocol in child, set parent as protocol object of the child in prepare(for segue: UIStoryboardSegue, sender: Any?), and call protocol methods whenever you want.
  3. Just post notification to NotificationCenter on child, and observe the notification on parent. Documentation of NotificationCenter, here you can find a brief example of using it.

Hope this helps!

PS: You can also observe properties of the child in the parent vc, if you want that way, I can explain.

like image 4
Fahri Azimov Avatar answered Nov 14 '22 00:11

Fahri Azimov