📒iPad使用UIAlertController报错了?

iPad使用UIAlertControllerStyleActionSheet容易掉坑里,先看错误信息:

*** Terminating app due to uncaught exception ‘NSGenericException’, reason: ‘Your application has presented a UIAlertController () of style UIAlertControllerStyleActionSheet. The modalPresentationStyle of a UIAlertController with this style is UIModalPresentationPopover. You must provide location information for this popover through the alert controller’s popoverPresentationController. You must provide either a sourceView and sourceRect or a barButtonItem. If this information is not known when you present the alert controller, you may provide it in the UIPopoverPresentationControllerDelegate method -prepareForPopoverPresentation.’

发生错误的代码如下:

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Choose the image", nil) message:@"" preferredStyle:UIAlertControllerStyleActionSheet];

UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
[alertController addAction:cancelAction];
    
UIAlertAction *photoAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Photo Album", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
[alertController addAction:photoAction];
    
UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Camera", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

    }];
[alertController addAction:cameraAction];
    
[self presentViewController:alertController animated:YES completion:nil];

解决的代码如下:

//在iPad中需要设置popoverPresentationController的sourceView、sourceRect、方向。

if (alertController.popoverPresentationController) {
    alertController.popoverPresentationController.sourceView = self.addImgView;
    alertController.popoverPresentationController.sourceRect = self.addImgView.bounds;
    alertController.popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionUp;
}

参考:http://stackoverflow.com/questions/26039229/swift-uialtertcontroller-actionsheet-ipad-ios8-crashes


📢原创文章📢
未经授权不得转载或转载请注明出处
本文地址: https://www.zhaoxiangguang.cn/note/ios/354.html

为您推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注