小编典典

使用 iOS 8 在 iPad 上正确呈现 UIAlertController

all

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

错位: 错位的图像

正确的: 在此处输入图像描述

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

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

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


阅读 73

收藏
2022-06-24

共1个答案

小编典典

您可以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
}
2022-06-24