How to access one UIViewControllers properties from another UIViewController?

爷,独闯天下 提交于 2019-12-25 00:33:25

问题


I have one single MainViewController which has of course it's one main UIView. I have this main view comprised of many different subviews.

Some of these subviews have their very own ViewController.

Lets say the MAIN view (whose delegate is primarily MainViewController) has a container which loads another UIView that uses a separate UIViewController- SecondaryViewController as the delegate for most it's actions.

This container view is of course loaded in MainViewController via

MyContainerViewController *myContainerController = 
         [[MyContainerViewController alloc] ...]; 
[self addSubView: myContainerController.view];

the controller for myContainerController.view though is MyContainerViewController. How inside this controller do I access MainViewController properties? Specifically I need to access MainViewController's - self.navigationController property to push a new ViewController? :)

Does this make any sense? I assume there's going to be casting of some sort involved since it seems I need to somehow retain a reference to MainViewController inside SecondaryViewController?


回答1:


It doesn't make sense to push a new ViewController from the SecondaryViewController in the MainViewController. This screws up the design of the code. A child object will access its parents method to call a method. By other words: bad code. Make a delegate call from the SecondaryViewController to the MainViewController that it state has changed. Then the MainViewController can decide to do with the call and the SecondaryViewController will not know anything about the implementation of the MainViewController.

So: Make a protocol in SecondaryViewController. Let the MainViewController be SecondaryViewController's delegate. Implement the delegate method in MainViewController which pushes the new ViewController.




回答2:


Expose the desired sub-view controllers as properties of the view controller that contains them.

Expose your root view controller(s) as properties of your app delegate, and synthesize them also.

When you want to access a different UIViewController, first obtain a reference to your appDelegate:

MyAppDelegate* myAppDelegate = [[UIApplication sharedApplication] delegate];

Then just use your chain of properties to get access to your desired view controller.

SubSubViewController* ssvc = myAppDelegate.rootViewController.subViewController.subSubViewController;

Some folks frown upon the use of the sharedApplication class method to obtain the reference to a delegate, but I've used it in multiple apps and not suffered for it (yet). The alternative is to pipe your appDelegate through your hierarchy of viewControllers.



来源:https://stackoverflow.com/questions/5010523/how-to-access-one-uiviewcontrollers-properties-from-another-uiviewcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!