美文网首页开发-使用技巧
UIAlertController中的坑

UIAlertController中的坑

作者: 稻草人的小秘密 | 来源:发表于2016-02-04 13:30 被阅读3178次
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"title" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    for (int i = 0; i < 10; i++) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:[NSString stringWithFormat:@"actionTitle%d",i] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertController addAction:action];
    }
    alertController.popoverPresentationController.sourceView = self.view;
    alertController.popoverPresentationController.sourceRect = CGRectMake(0,0,1.0,1.0);
    [self presentViewController:alertController animated:YES completion:nil];
    

    当在iPad上运行上面这段代码的时候,如果没有设置如下两个属性 alertController.popoverPresentationController.sourceView
    alertController.popoverPresentationController.sourceRect
    会导致程序crash。然而在iPhone上没有这样的问题。

    错误提示内容如下:

    Terminating app due to uncaught exception 'NSGenericException', reason: 'Your application has presented a UIAlertController (<UIAlertController: 0x14f735790>) 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* 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];
    

    然而上面的这段代码摘自官方文档,比较之后是因为preferredStyle不同引起的。当然也和设备类型有关系,是一个比较容易忽略的地方。

    相关文章

      网友评论

        本文标题:UIAlertController中的坑

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