在 iOS 8.0 中,Apple 引入了 UIAlertController 来替换 UIActionSheet 。不幸的是,Apple 没有添加任何有关如何呈现它的信息。我在 hayaGeek 的博客上找到了关于它的 entry,但是,它似乎不适用于 iPad。该 View 完全放错了位置:

错位:
ios - 使用 iOS 8 在 iPad 上正确呈现 UIAlertController-LMLPHP

正确的:
ios - 使用 iOS 8 在 iPad 上正确呈现 UIAlertController-LMLPHP

我使用以下代码在界面上显示它:

    let alert = UIAlertController()
    // setting buttons
    self.presentModalViewController(alert, animated: true)

有没有其他方法可以为 iPad 添加它?或者苹果只是忘记了 iPad,或者还没有实现?

最佳答案

您可以使用 UIAlertController 从弹出窗口显示 UIPopoverPresentationController
在 Obj-C 中:

UIViewController *self; // code assumes you're in a view controller
UIButton *button; // the button you want to show the popup sheet from

UIAlertController *alertController;
UIAlertAction *destroyAction;
UIAlertAction *otherAction;

alertController = [UIAlertController alertControllerWithTitle:nil
                                                      message:nil
                           preferredStyle:UIAlertControllerStyleActionSheet];
destroyAction = [UIAlertAction actionWithTitle:@"Remove All Data"
                                         style:UIAlertActionStyleDestructive
                                       handler:^(UIAlertAction *action) {
                                           // do destructive stuff here
                                       }];
otherAction = [UIAlertAction actionWithTitle:@"Blah"
                                       style:UIAlertActionStyleDefault
                                     handler:^(UIAlertAction *action) {
                                         // do something here
                                     }];
// note: you can control the order buttons are shown, unlike UIActionSheet
[alertController addAction:destroyAction];
[alertController addAction:otherAction];
[alertController setModalPresentationStyle:UIModalPresentationPopover];

UIPopoverPresentationController *popPresenter = [alertController
                                              popoverPresentationController];
popPresenter.sourceView = button;
popPresenter.sourceRect = button.bounds;
[self presentViewController:alertController animated:YES completion:nil];
为 Swift 4.2 进行编辑,虽然有很多相同的博客可用,但它可能会节省您去搜索它们的时间。
if let popoverController = yourAlert.popoverPresentationController {
    popoverController.sourceView = self.view //to set the source of your alert
    popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0) // you can set this as per your requirement.
    popoverController.permittedArrowDirections = [] //to hide the arrow of any particular direction
}

关于ios - 使用 iOS 8 在 iPad 上正确呈现 UIAlertController,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24224916/

10-14 20:08
查看更多