UIPopoverPresentationController not showing rightBarButtonItems in iOS 11

345 views Asked by At

I'm trying to show a UIPopoverPresentationController which has a UIButton in it's navigation bar. This used to work, but the UIButton is not showing anymore, since iOS 11 (iPad). Interestingly, in my popup, I can also push another UIViewController, and when I come back from it, the UIButton appears. Here's the code to show the popup:

- (IBAction)buttonPressed:(id)sender {
    PopupViewController *popupController = [self.storyboard instantiateViewControllerWithIdentifier:@"PopupController"];

    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:popupController];
    navController.modalPresentationStyle = UIModalPresentationPopover;
    [self presentViewController:navController animated:YES completion:nil];

    UIPopoverPresentationController *popController = [popupController popoverPresentationController];

    CGRect rect = self.button.frame;

    CGSize size = CGSizeMake(500, 400);
    popController.sourceView = self.view;
    popController.sourceRect = rect;
    popupController.preferredContentSize = size;
} 

and here is the code in the popup, to show the UIButton:

- (void)viewWillAppear:(BOOL)animated
{
    UIButton *rightButton = [[UIButton alloc]init];
    [rightButton setTitle: @"Press me" forState:UIControlStateNormal];
    [rightButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    rightButton.frame = CGRectMake(0, 0, 120, 24);

    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    UIBarButtonItem *flexible = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:flexible, rightButtonItem, nil];
    self.navigationController.preferredContentSize = self.preferredContentSize;
}

Does anybody know what's going on? Why is the button now showing right away?

1

There are 1 answers

0
pmacro On

I would move your code out of viewWillAppear and into viewDidLoad. Its being in viewWillAppear is the reason you can see the button when you open another controller and then go back to this one, but you don't really want the button to be recreated every time you go back to this view. I think there's a good chance this will fix the problem of it not showing at first, too.