Presenting a UIPopoverController from UICollection

2020-07-11 10:05发布

问题:

I'm looking to present a UIPopoverController from a button on a UICollectionViewCell.

So far, everything is created ok, but the popover isn't visible.

Is there a special way of doing this?

The code works if I display it from anything else other than a collection view cell.

The following code is in the UICollectionViewCell subclass.

if (_infoPopover == nil) {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
    GameInfoViewController *gameInfoVC = (GameInfoViewController *)[storyboard instantiateViewControllerWithIdentifier:@"GameInfoViewController_ID"];

    UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:gameInfoVC];
    _infoPopover = popover;
    [gameInfoVC setGameNameString:_gameNameLabel.attributedText];
}

[_infoPopover presentPopoverFromRect:_infoButton.frame inView:self permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];

Thanks!

回答1:

Perform PopOver from UIViewController, not in UICollectionViewCell. So, use delegate to control.

//Cell.m
-(void)popOVerClick:(UIButton *)button{
    [[self delegate] didPopOverClickInCell:self];
}

implement protocol

//ViewController
    -(void)didPopOverClickInCell:(MyCell *)cell{
    if ([self.flipsidePopoverController isPopoverVisible]) {
        [self.flipsidePopoverController dismissPopoverAnimated:YES];
    } else {

        FlipsideViewController *controller = [[FlipsideViewController alloc] initWithNibName:@"FlipsideViewController" bundle:nil];
        controller.label.text = cell.title;
        controller.delegate = self;

        self.flipsidePopoverController = [[UIPopoverController alloc] initWithContentViewController:controller];
        [self.flipsidePopoverController presentPopoverFromRect:cell.frame inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    }
}

And the code for you: https://github.com/lequysang/TestPopOver



回答2:

change inView to collectionView

[_infoPopover presentPopoverFromRect:_infoButton.frame inView:self.collectionView permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];