iPad使用UIAlertControllerStyleActionSheet容易掉坑里,先看错误信息:
*** Terminating app due to uncaught exception ‘NSGenericException’, reason: ‘Your application has presented a UIAlertController (<UIAlertController: 0x7ff87f7f4f60>) 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