How to initialize popover view from UICollectionViewCell in IOS

最后都变了- 提交于 2019-12-10 15:44:26

问题


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?


回答1:


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"];

Happy coding!



来源:https://stackoverflow.com/questions/21566387/how-to-initialize-popover-view-from-uicollectionviewcell-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!