Should I call dismissViewController on the modal UIViewController or the UIViewController that presented it?

人盡茶涼 提交于 2019-12-11 13:43:51

问题


It seems to work in either case, but why and how, and which is the best way?


回答1:


Why and How

Let's say, view controller A has presented B, and B has presented C in turn.

When you call dismissViewControllerAnimated:completion:, iOS checks to see if the view controller you're calling it on has a child in its presentedViewController property. If it does, then it dismisses that controller.

So if I call it on B in our example, it dismisses C, but if I call it on A, it dismisses B (which takes away C with it).

If I call it on C, then it has no child. So then iOS checks the presentingViewController property. If that is set, it asks it to dismiss its controller. So if I call it on C, iOS sends the request back to B, which dismisses C.

So calling the method on either B or C will get rid of C, while calling it on A gets rid of B and C.

Best Practice

Call it on B, on the thing that presented, every time. This is

  1. less confusing, since your present and dismiss will be in the same place, and

  2. more future proof, since at some point in the future you may make C present yet another view controller (D), and then the dismissal would suddenly break (it would suddenly start dismissing D, rather than dismissing itself).



来源:https://stackoverflow.com/questions/18047430/should-i-call-dismissviewcontroller-on-the-modal-uiviewcontroller-or-the-uiviewc

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