如何在UIBarbutton中将UIAlertcontroller实现为PopOver(箭头方向向上)

我知道这是一个旧学校的问题 – 但我确实搜查了networking,发现解决scheme将被弃用。 我将如何实现一个UIAlertcontroller作为popOver(箭头方向向上)barButton 。 代码如下:

- (IBAction)eventSortingAction:(UIBarButtonItem *)sender { UIAlertController * view= [UIAlertController alertControllerWithTitle:@"My Title" message:@"Select you Choice" preferredStyle:UIAlertControllerStyleActionSheet]; UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) { //Do some thing here [view dismissViewControllerAnimated:YES completion:nil]; }]; UIAlertAction* cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) { [view dismissViewControllerAnimated:YES completion:nil]; }]; [view addAction:ok]; [view addAction:cancel]; [view setModalPresentationStyle:UIModalPresentationPopover]; view.modalInPopover = YES; view.popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionUp; view.popoverPresentationController.delegate = self; [self presentViewController:view animated:YES completion:nil]; UIView* senderView = [sender valueForKey:@"view"]; //HACK UIPopoverPresentationController* popover = view.popoverPresentationController; if (popover) { popover.sourceView = senderView; popover.sourceRect = senderView.bounds; popover.permittedArrowDirections = UIPopoverArrowDirectionUp; popover.barButtonItem = self.actionBarButton; popover.delegate = self; }} 

显然我总是得到“popover = nil”。 请帮忙! 提前致谢!

顺便说一句,这个代码不是我的,只是在Xcode中testing它。

提醒一下,因为这是Google的最高成绩:

popPresenter.barButtonItem是替代popPresenter.sourceView + popPresenter.sourceRect

看 (来源)

关于OP问题,应该使用IBAction参数sender

 UIPopoverPresentationController *popPresenter = [alertController popoverPresentationController]; popPresenter.barButtonItem = sender; [self presentViewController:alertController animated:YES completion:nil]; 
 UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet]; UIAlertAction *actnCamera = [UIAlertAction actionWithTitle:@"Camera" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) { }]; UIAlertAction *actnLibrary = [UIAlertAction actionWithTitle:@"Library" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) { }]; [alertController addAction:actnLibrary]; [alertController addAction:actnCamera]; [alertController setModalPresentationStyle:UIModalPresentationPopover]; UIPopoverPresentationController *popPresenter = [alertController popoverPresentationController]; popPresenter.sourceView = self.view; CGRect frame = self.navigationController.navigationBar.frame; frame.origin.x = self.navigationItem.leftBarButtonItem.width; popPresenter.sourceRect = frame; popPresenter.barButtonItem = self.navigationItem.leftBarButtonItem; [self presentViewController:alertController animated:YES completion:nil]; 

OUTPUT

在这里输入图像说明