美文网首页
UIAlertController适配iPad

UIAlertController适配iPad

作者: OwenWong | 来源:发表于2019-07-26 11:43 被阅读0次

    问题: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;//箭头指向
        }
    

    相关文章

      网友评论

          本文标题:UIAlertController适配iPad

          本文链接:https://www.haomeiwen.com/subject/hqerrctx.html