Runtime Exception coming when show UIAlertControll

2020-03-26 08:23发布

问题:

Runtime exception is coming when i show UIAlertController(ActionSheet) in iOS8 Beta5+ Xcode6.

This Bug is only happening in iPad Devices.

I'm getting bellow exception when using the UIAlertController.

* Terminating app due to uncaught exception 'NSGenericException', reason: 'UIPopoverPresentationController (<_UIAlertControllerActionSheetRegularPresentationController: 0x15794370>) should have a non-nil sourceView or barButtonItem set before the presentation occurs.'

My Code for display ActionSheet as follows

     // Cancel Button
      UIAlertAction *actionCancel = [UIAlertAction
                                               actionWithTitle:NSLocalizedString(@"IDS_LABEL_CANCEL", nil)
                                               style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                                                   // cancel
                                                   //action handler
                                                   [self actionHandler:nil withTag:0 withButtonIndex:0];
                                               }];

      // print button
      UIAlertAction *actionPrint = [UIAlertAction
                                                      actionWithTitle:NSLocalizedString(@"IDS_LABEL_PRINT", nil)
                                                      style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {

                                                          //action handler
                                                          [self actionHandler:nil withTag:kAttachmentActionSheetTag withButtonIndex:0];         
                                             }];

    // Create action sheet
     UIAlertController *alertController = [UIAlertController
                                                      alertControllerWithTitle:nil message:nil
                                                      preferredStyle:UIAlertControllerStyleActionSheet];

[alertController addAction:actionCancel];
[alertController addAction:actionPrint];

     // show aciton sheet
     [self  presentViewController:alertController animated:YES
                                 completion:nil] ;

回答1:

On iPad the alert will be displayed as a popover using the new UIPopoverPresentationController, it requires that you specify an anchor point for the presentation of the popover using one of the three following properties:

  • barButtonItem
  • sourceView
  • sourceRect

In order to specify the anchor point you will need to obtain a reference to the UIAlertController's UIPopoverPresentationController and set one of the properties as follows:

alertController.popoverPresentationController.sourceView = parentView;