Dismissing iPad UIPopoverController when BarButtonItem is pushed while it's open

后端 未结 7 1194
闹比i
闹比i 2020-12-14 11:36

Using a split view on the iPad, I have the following code:

- (void) splitViewController:(UISplitViewController *)svc willHideViewController:(UIViewController         


        
7条回答
  •  借酒劲吻你
    2020-12-14 12:11

    Apple's HIG says there should not be an explicit dismiss button inside a popover, but to do what you're asking, you have two options.

    1) post an NSNotification

    OR

    2) drill down into your view hierarchy until you have the popover instance

    1) in whichever view you are presenting the popover in, in the viewDidLoad method:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismissThePopover) name:@"popoverShouldDismiss" object:nil];
    

    create a method called "dismissThePopover" and in the dealloc method, removeObserver

    -(void)dismissThePopover {
        [self.popoverController dismissPopoverAnimated:YES];
    }
    
    -(void)dealloc {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    

    In your popoverController "dismiss" button, enter this line:

    [[NSNotificationCenter defaultCenter] postNotificationName:@"popoverShouldDismiss" object:nil];
    

    Doing that sends a notification to the app, and since you've registered your other view controller to listen for it, whenever it sees that notification it calls the selector you specify, in this case, dismissThePopover.

    2) drill down into your view hierarchy to find self.popoverController

    check this out, yours will be different, surely, but the overall idea is the same. Start at your AppDelegate, move into the first viewcontroller, move into subviews until you get to your self.popoverController object.

    MyAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
    //appDelegate instance, in this case it's the .m file for your ApplicationDelegate
    
    UISplitViewController *svc = appDelegate.splitViewController;
    //In this case the first view inside the appDelegate is a SplitView, svc
    
    UINavigationController *navc = [[svc viewControllers]objectAtIndex:0];
    //a navigationController is at index:0 in the SplitView hierarchy. DetailView is at index:1
    
    NSArray *vcs = [navc viewControllers];
    //vcs is the array of different viewcontrollers inside the Navigation stack for nvc
    
    iPadRootViewController *rootView = [vcs objectAtIndex:0];
    //declare the rootView, which is the .m file that is at index:0 of the view array
    
    UIPopoverController *pc = [rootView popoverController];
    //HERE WE GO!!! popoverController is a property of iPadRootViewController's instance rootView, hereby referred to as pc.
    
    [pc dismissPopoverAnimated:YES];
    //bye bye, popoverController!
    

    Hope this helps

提交回复
热议问题