Search code examples
objective-cuipopovercontrolleruipopoverbackgroundview

How to add dimmed background to a custom UIPopoverBackgroundView


I am making custom popover by subclassing UIPopoverBackgroundView (using this tutorial) and presenting it by using UIPopoverController. Unfortunately as soon as I specify custom popoverBackgroundViewClass the native dimmed background disappears. Is there any way to leave the dimmed background when using custom UIPopoverBackgroundView? Any other solution that I can use to simulate native behaviour?


Solution

  • Not sure why this got down voted, it's a good question because when you implement a custom UIPopoverBackgroundView, the dimmed background doesn't get set. In researching this problem, I determined the best approach is to set it myself!

    Just before creating the popover view, I create a "mask view" that will be added to the view before the popover. This code includes a nice fade in effect as well:

    self.customPopoverMaskView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
        self.customPopoverMaskView.backgroundColor = [UIColor blackColor];
        self.customPopoverMaskView.alpha = 0.3f;
    
        [UIView transitionWithView:self.view
                          duration:0.3
                           options:UIViewAnimationOptionTransitionCrossDissolve
                        animations:^ {
                            [self.view addSubview:self.customPopoverMaskView];
                        }
                        completion:nil];
    

    And to remove the view, plug this into the method(s) that handle the popover view disappearing:

    [UIView transitionWithView:self.view
                      duration:0.3
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:^ {
                        [self.customPopoverMaskView removeFromSuperview];
                    }
                    completion:nil];
    

    Works well for me. Happy coding!

    Aaron