UIAlertController适配iPad

2019-07-26  本文已影响0人  OwenWong

问题:UIAlertControllerStyleAlert/UIAlertControllerStyleActionSheet在iPhone上运行正常,iPad却崩溃

错误信息:
Your application has presented a UIAlertController (<UIAlertController: 0x102c1a600>) of style UIAlertControllerStyleActionSheet from ViewController (< ViewController: 0x102b56200>). 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的写法如下:

UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"My Alert"
                           message:@"This is an alert."
                           preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
    handler:^(UIAlertAction * action) {}];

[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];

此时,iPhone上运行OK,iPad崩溃。原因在于:UIAlertController在iPad上需指定展示在哪个view上,自定义其frame。方法如下:

UIPopoverPresentationController *popover = alert.popoverPresentationController;
    if (popover)
    {
        popover.sourceView = self.view;// 在哪个view上展示
        popover.sourceRect = CGRectMake(0, 0, 100, 100);// 自定义frame
        popover.permittedArrowDirections = UIPopoverArrowDirectionDown;//箭头指向
    }
上一篇下一篇

猜你喜欢

热点阅读