iPad调用UIAlertController在UIAlertControllerStyleActionSheet下崩溃问题

2023年4月3日 654点热度 0人点赞 0条评论
问题状态:

Thread 1: "UIPopoverPresentationController (<UIPopoverPresentationController: 0x12f33b020>) should have a non-nil sourceView or barButtonItem set before the presentation occurs."

 

问题原因

iPad中UIAlertController的UIAlertControllerStyleActionSheet样式和iOS的实现方法有细微差别,iOS中是底部屏幕弹出,而iPad 因为其屏幕大的原因,弹窗是以气泡形式展现的,而气泡的形式需要提供气泡展示的位置与载体,在找不到相关实现的情况下,App Crash

解决方法

在使用UIAlertControllerStyleActionSheet样式的情况下,需要区分是iPad还是iPhone,或者其他设备;

Obj-C方法

UIButton *button; // 如在button按钮的点击实现  UIAlertController 选项

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil
                                                      message:nil
                           preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *destroyAction = [UIAlertAction actionWithTitle:@"删除"
                                         style:UIAlertActionStyleDestructive
                                       handler:^(UIAlertAction *action) {
                                           // do destructive stuff here
                                       }];
UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"返回"
                                       style:UIAlertActionStyleDefault
                                     handler:^(UIAlertAction *action) {
                                         // do something here
                                     }];
[alertController addAction:destroyAction];
[alertController addAction:otherAction];

方法一:判断是有popPresenter,iPhone默认是没有的

UIPopoverPresentationController *popPresenter = [alertController popoverPresentationController]; // 获取alertController 样式
if (popPresenter) {
    popPresenter.sourceView = button; // 在哪个View上显示
    popPresenter.sourceRect = button.bounds; // 指定箭头指向区域与大小
    [self presentViewController:alertController animated:YES completion:nil];
}



方法二:判断设备
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
    UIPopoverPresentationController *popPresenter = [alertController popoverPresentationController]; // 获取alertController 样式
    popPresenter.sourceView = button; // 在哪个View上显示
    popPresenter.sourceRect = button.bounds; // 指定箭头指向区域与大小
    [self presentViewController:alertController animated:YES completion:nil];
}

 

Swift 4.2+

/// Swift 4.2+

方法一:按类型
if let popoverController = yourAlert.popoverPresentationController {
    popoverController.sourceView = button
    popoverController.sourceRect = button.bounds
}

方法二:按设备
if (UIDevice.current.userInterfaceIdiom == .pad) {
  /// .... 省略,请参考Obj-C 实现
}

 

帮助教程

提供最新的帮助教程,方便使用。

文章评论