How to add dimmed background to a custom UIPopover

2020-06-04 13:17发布

问题:

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?

回答1:

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



回答2:

All you need is add next code into initWithFrame: method of your implementation of UIPopoverBackgroundView.

UIView *dimView = [[UIView alloc] initWithFrame:CGRectMake(0 - self.frame.origin.x,
                                                           0 - self.frame.origin.y,
                                                           [UIScreen mainScreen].bounds.size.width,
                                                           [UIScreen mainScreen].bounds.size.height)];
dimView.backgroundColor = [UIColor blackColor];
dimView.alpha = 0.15;
dimView.userInteractionEnabled = NO;
[self addSubview:dimView];

It works as same as default Apple implementation.