How to add dimmed background to a custom UIPopoverBackgroundView

前端 未结 2 1259
旧巷少年郎
旧巷少年郎 2021-02-10 04:44

I am making custom popover by subclassing UIPopoverBackgroundView (using this tutorial) and presenting it by using UIPopoverController. Unfortunately as soon as I specify custom

相关标签:
2条回答
  • 2021-02-10 05:05

    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.

    0 讨论(0)
  • 2021-02-10 05:22

    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

    0 讨论(0)
提交回复
热议问题