UIAlertController崩溃了(iPad)

43

我正在使用 Xcode 6 开发 iOS 应用程序。

当我使用 UIAlertController 时,在 iPhone 6 模拟器上可以正常工作,但在 iPad 模拟器上崩溃了。

我的问题是,在点击“分享”时,它可能会崩溃。我该怎么解决?

这是我的代码:

override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject] {
    
    var shareAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Share", handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in
        
        let shareMenu = UIAlertController(title: nil, message: "Share using", preferredStyle: .ActionSheet)
        let twitterAction = UIAlertAction(title: "Twitter", style: UIAlertActionStyle.Default, handler: nil)
        let facebookAction = UIAlertAction(title: "Facebook", style: UIAlertActionStyle.Default, handler: nil)
        let emailAction = UIAlertAction(title: "Email", style: UIAlertActionStyle.Default, handler: nil)
        let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)
        
        shareMenu.addAction(twitterAction)
        shareMenu.addAction(facebookAction)
        shareMenu.addAction(emailAction)
        shareMenu.addAction(cancelAction)
        
        self.presentViewController(shareMenu, animated: true, completion: nil)
        }
    )

Xcode显示了这条消息:

******Terminating app due to uncaught exception 'NSGenericException', reason: 'Your application has presented a UIAlertController (<UIAlertController: 0xaf71c80>) 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.'
*** First throw call stack:
(
    0   CoreFoundation                      0x0023c746 __exceptionPreprocess + 182
    1   libobjc.A.dylib                     0x01c7aa97 objc_exception_throw + 44
    2   UIKit                               0x012c4062 -[UIPopoverPresentationController presentationTransitionWillBegin] + 3086
    3   UIKit                               0x00bda174 __71-[UIPresentationController _initViewHierarchyForPresentationSuperview:]_block_invoke + 1549
    4   UIKit                               0x00bd8247 __56-[UIPresentationController runTransitionForCurrentState]_block_invoke + 198
    5   UIKit                               0x00c0d31b __40+[UIViewController _scheduleTransition:]_block_invoke + 18
    6   UIKit                               0x00ac6862 ___afterCACommitHandler_block_invoke + 15
    7   UIKit                               0x00ac680d _applyBlockToCFArrayCopiedToStack + 415
    8   UIKit                               0x00ac6622 _afterCACommitHandler + 549
    9   CoreFoundation                      0x0015d86e __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 30
    10  CoreFoundation                      0x0015d7b0 __CFRunLoopDoObservers + 400
    11  CoreFoundation                      0x001531ea __CFRunLoopRun + 1226
    12  CoreFoundation                      0x00152a5b CFRunLoopRunSpecific + 443
    13  CoreFoundation                      0x0015288b CFRunLoopRunInMode + 123
    14  GraphicsServices                    0x047b82c9 GSEventRunModal + 192
    15  GraphicsServices                    0x047b8106 GSEventRun + 104
    16  UIKit                               0x00a9c106 UIApplicationMain + 1526
    17  Mars I                              0x0001c724 main + 180
    18  libdyld.dylib                       0x02392ac9 start + 1
    19  ???                                 0x00000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException******

苹果表示,如果您想呈现任何视图控制器,并且它的类型为AlertViewController,则应该将其呈现在弹出窗口中,而不是独立的视图,因为这涉及到用户体验的问题。 - Ruchish Shah
11个回答

60

为了保持设备的独立性,建议按照下面代码片段所示的方式使用它。此代码将在 iPhone / 紧凑尺寸设备上返回 nil,因此您可以在通用项目中安全地使用它。

if let popoverPresentationController = shareMenu.popoverPresentationController {
    popoverPresentationController.sourceView = self.view
    popoverPresentationController.sourceRect = sender.bounds
}
self.presentViewController(shareMenu, animated: true, completion: nil)

9
刚在iOS10上遇到了这个问题,不认为它已经修复。 - deloki
2
实际上,您不需要执行if let检查,因为如果popoverPresentationControllernil,则不会设置任何内容。 - Harish
1
应该使用sender而不是self.view来显示正确的箭头方向,.sourceView。 - Adam Smaka
没错,只需要 popoverPresentationController?.sourceView = self.viewpopoverPresentationController?.sourceRect = sender.bounds 就足够了。 - Harry Bloom
2
在这种情况下,“sender”到底是什么? 它是执行操作的视图吗? - Ichor de Dionysos
2
是的,发送者是触发操作的UIControl或UIView。 - Karoly Nyisztor

41

尝试这段代码:

shareMenu.popoverPresentationController.sourceView = self.view
shareMenu.popoverPresentationController.sourceRect = CGRectMake(self.view.bounds.size.width / 2.0, self.view.bounds.size.height / 2.0, 1.0, 1.0)

self.presentViewController(shareMenu, animated: true, completion: nil)

1
你能解释一下 CGRectMake(self.view.bounds.size.width / 2.0, self.view.bounds.size.height / 2.0, 1.0, 1.0) 的意思吗? - Cerlin
@CerlinBoss 这个定义了一个在视图中心的1像素正方形,用于指示菜单箭头的指向。 - Cœur

12

Swift 4

popoverPresentationController.permittedArrowDirections = .init(rawValue: 0)
popoverPresentationController.sourceView = self.view
popoverPresentationController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)

12

参考:在Swift中iPad上的ActionSheet Popover

创建popoverController:

let alertController = UIAlertController(title: nil, message: "Alert message.", preferredStyle: .actionSheet)
self.present(alertController, animated: true, completion: nil)

如果您想要显示带有指示器视图的警告框,应该:

if let popoverController = alertController.popoverPresentationController {
    popoverController.barButtonItem = sender
}

带指示器

with indicator

在中心显示警告:

if let popoverController = alertController.popoverPresentationController {
  popoverController.sourceView = self.view
  popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0) 
}

center with indicator

无指示器的居中:

if let popoverController = alertController.popoverPresentationController {
  popoverController.sourceView = self.view
  popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
  popoverController.permittedArrowDirections = []
}

center no indicator


7
我也遇到了同样的问题,最终找到了解决方案。这是我为Objective-C提供的解决方案:
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Select you option:"
                                                                         message:nil
                                                                  preferredStyle:UIAlertControllerStyleActionSheet];

UIAlertAction *action = [UIAlertAction actionWithTitle:@“share”
                                                     style:UIAlertActionStyleDefault
                                                   handler:^(UIAlertAction *action) {
                                                       // do other things
                                                   }];
[alertController addAction:action];

UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel"
                                                       style:UIAlertActionStyleCancel
                                                     handler:^(UIAlertAction *action) {
                                                     }];
[alertController addAction:cancelAction];

// Remove arrow from action sheet.
[alertController.popoverPresentationController setPermittedArrowDirections:0];

//For set action sheet to middle of view.
CGRect rect = self.view.frame;
rect.origin.x = self.view.frame.size.width / 20;
rect.origin.y = self.view.frame.size.height / 20;
alertController.popoverPresentationController.sourceView = self.view;
alertController.popoverPresentationController.sourceRect = rect;

[self presentViewController:alertController animated:YES completion:nil];

好奇为什么我们要除以20。我尝试了2.0,但它放在右下角了。几何方面还有一些不清楚的地方。 - SpaceTrucker
Swift 4 去除箭头: popoverPresentationController.permittedArrowDirections = .init(rawValue: 0) - kurtanamo

2

我使用这个方便的扩展来创建不会崩溃的操作表。

extension UIAlertController {

    class func actionSheetWith(title: String?, message: String?, sourceView: UIView?, sourceFrame: CGRect?) -> UIAlertController {
        let actionController = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
        if actionController.responds(to: #selector(getter: popoverPresentationController)) {
            actionController.popoverPresentationController?.sourceView = sourceView ?? StoryboardHelper.tabBarControllerTopController()?.view
            actionController.popoverPresentationController?.sourceRect = sourceFrame ?? CGRect(x: 0, y: 0, width: 0, height: 0)
        }
        return actionController
    }

}

1
我使用这段代码,非常简单易懂,也许我可以帮助任何人。
//if iPhone
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
        [self presentViewController:actionSheet animated:YES completion:nil];
    }
    //if iPad
    else {
        // Change Rect to position Popover
        UIPopoverController *popup = [[UIPopoverController alloc] initWithContentViewController:actionSheet];
        [popup presentPopoverFromRect:CGRectMake(self.view.frame.size.width/2, self.view.frame.size.height/4, 0, 0)inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    }

1

我发现这个链接很有用,对我起作用了

https://medium.com/@nickmeehan/actionsheet-popover-on-ipad-in-swift-5768dfa82094

我对以下内容进行了微小的更改,以调整对齐方式。
if let popoverPresentationController = alert.popoverPresentationController {
        popoverPresentationController.sourceView = self.view
        popoverPresentationController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.size.height * 0.85, width: 0, height: 0)
        popoverPresentationController.permittedArrowDirections = []
    }

0

迅捷 3

shareMenu.popoverPresentationController?.sourceView = self.view
shareMenu.popoverPresentationController?.sourceRect = 
    CGRect(x: view.bounds.size.width, 
           y: view.bounds.size.height-80, 
           width: 1.0, height: 1.0)

源矩形是您想要显示弹出视图的点。


0

如果您不需要将警报显示为弹出窗口,可以在初始化AlertViewController时使用UIAlertController.Style.alert作为首选样式。

let shareMenu = UIAlertController(title: nil, message: "Share using", preferredStyle: .alert)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接