Dismissing a UIPopoverController from within its contentViewController?

风流意气都作罢 提交于 2019-12-21 03:26:05

问题


If you want to dismiss a popover -- for example, from a button within the popover's contentViewController you must --

  1. Create a reference to the popover to be held by view controller which creates it
  2. Create a notification from the contentViewController to let the owning view controller know that it should be dismissed, or alternately create a delegate for the same purpose
  3. Send the notification or delegate message when the popover is ready to be dismissed
  4. Call dismissPopover:animated when the notification or delegate method is called

Meanwhile, from a UIViewController you can access the modal view controller, the parent view controller, the navigation controller, the split view controller, the tab bar controller, the search display controller, the child view controllers, the presenting view controllers, and the presented view controllers.

Is there a better approach to do this from popover's contentViewController?


回答1:


Unfortunately, you'll have to create a weak property reference to said UIPopoverController as there's no way to access it from within the content view controller.

I was surprised how UIViewControllers can access the modal view controller, the parent view controller, the navigation controller, the split view controller, the tab bar controller, the search display controller, and as of iOS 5, the child view controllers as well as presenting and presented controllers...but not the popover controller (granted popovers aren't UIViewControllers but still).

Technically, there's a private, undocumented method to retrieve the popoverController that the UIViewController is in...I have no idea why they never made it public given that it should be exactly the same as any of the above controllers.

Though even in the private, undocumented world, there's no equivalent to dismissModalViewcontrollerAnimated:. You'll still have to get that reference then dismiss it that way.




回答2:


Another way to solve this is to create an abstract view controller (for all your view controllers) that adds an NSNotification observer to a method such as -(void)closePopoverIfNecessary:(NSNotification*)notification and have child classes optionally implement the method to close their popover(s) if open. Then from within the popover's controller you fire the notification to close it. You could also pass other info via the notification (userInfo) if needed.

This way there's no need for the parent references.



来源:https://stackoverflow.com/questions/9877729/dismissing-a-uipopovercontroller-from-within-its-contentviewcontroller

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