Domanda

I've been tracking along with an iPad app using storyboards, and I've been stuck on this for days. How can I initiate a popover segue by selecting a cell in a collection view? The main problem is getting past the error that the popover must be anchored to a view.

The approach seems to be putting a dummy popoverAnchorButton (hidden, disabled) in the view, create a segue from it to the popover view in the storyboard, position it in didSelectItemAtIndexPath, and then [self performSegue]. Code looks like this:

- (IBAction)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

    [self.collectionView deselectItemAtIndexPath:indexPath animated:NO];
    UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
    CGRect anchorRect = CGRectMake(cell.center.x, cell.center.y, 1.0f, 1.0f);
    self.popoverAnchorButton.frame = anchorRect;
    [self performSegueWithIdentifier:@"popoverSegue" sender:self];
}

This works elsewhere in the app in a table view, because the storyboard lets me drop a button in the view, to use as an anchor point. But Xcode doesn't let me drop a button or any other suitable view into the collection view in the storyboard, so I can't create the segue. Creating the button programmatically is no help, because I can't build a UIStoryboardSegue from it, and any manual segue from the controller gives the same error about lacking an anchor point. Any ideas?

I think another path could be to skip segues and instantiate the popover view controller programmatically, but the roadblock here is an error stemming from the fact that the popover view I create (since I'm using storyboards) has no xib. Do I have to create a separate xib file just for this popover view? Is that the only option?

È stato utile?

Soluzione

If you are interested in getting the CGRect of the currently selected cell in the collection view you might use:

CGRect rect = [collectionView layoutAttributesForItemAtIndexPath:indexPath].frame;

And after that you can display your popover from that rect using presentPopoverFromRect:inView:permittedArrowDirections:animated: of your UIPopoverController.

And yes, you can always dynamically load a VC from your storyboard if it has a storyboard identifier associated to it:

UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"YourStoryboardName" bundle:nil];
UIViewController* vc = [storyboard instantiateViewControllerWithIdentifier:@"YourIdentifier"];

In case you are calling the code from a VC loaded from storyboard itself, instead you can use:

UIViewController* vc = [self.storyboard instantiateViewControllerWithIdentifier:@"YourIdentifier"];
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top