UIPopoverController: Why my popover doesn't ap

2019-05-01 19:00发布

问题:

Simple: A view, i present a UIPopoverController in a CGRect using presentPopoverFromRect... and neither the arrow or the popover frame appear even near to the coordinates i asked for in the rect i passed into. Any clues? I've been trying to figure out this by myself but am giving up. Here is the code:

if(!myContentController){
    myContentController = [[MyContentController alloc] initWithNibName:myNibName bundle:[NSBundle mainBundle]];
    // This works pretty well. actually when i show the popover
    // i see everything inside as it's supposed to.
}
if(!popover){
   popover = [[UIPopoverController alloc] initWithContentViewController:myContentController];
}
else{
    [popover setContentController:myContentController];
}
popover.delegate = self;
CGPoint touchPointInView = [self touchPoint];//This is working fine too.I've been checking with NSLog.
popover.ContentSize = myPopoverSize;//In this case {320,480}
 [popover presentPopoverFromRect:CGRectMake(touchPoint.x,touchPoint.y,myPopoverSize.width,myPopverSize.height)
                          inView:self.view
        permittedArrowDirections:UIPopoverArrowDirectionAny
                        animated:YES];

What happens next? the popover doesn't shows where it should be. If i pass {0,0} it shows in the middle of the screen as if the view size were (768,512). I checked all the view dimensions and they are all ok, frame,bounds, etc... . Does anyone knows what am i doing wrong?

回答1:

The CGRect you give to presentPopoverFromRect is the rect that it will display the popover next to (not in). Depending on the location of the rect, the popover will appear on an appropriate side of the specified rect.

If you want the popover to appear at a specific point, give it a rect with the origin as the point and the size as 1,1. So the CGRectMake in the presentPopoverFromRect line should be:

CGRectMake(touchPoint.x,touchPoint.y,1,1)

Also make sure that the touchPoint is relative to the inView (self.view in your case).


By the way, there are a few other errors in the code (probably just typos in the question):

  • setContentController should be setContentViewController
  • popover.ContentSize should be popover.popoverContentSize
  • myPopverSize.height should be myPopoverSize.height (but this will be replaced by 1)


回答2:

In my case the reason of this problem was following. It is also possible, that your view is a tableView. So, when you scroll it and try to show UIPopover in a rect in that tableView, it may not be shown. I used this:

[_popoverController presentPopoverFromBarButtonItem:self.navigationItem.rightBarButtonItem permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];