はじめに
UIAlertControllerを表示する際に2点課題がありました。
・常にRootViewControllerから出したい
・表示処理を実行しても実際に表示されるまで1秒ほど待たされる現象がある
そこで、その対応を含んだAlert表示用処理を使い
すべてのAlertをこのメソッド経由で出すようにしています。
UIAlertController表示用メソッド
+ (void)showAlertController:(UIAlertController *)alertController
{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.0001 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
UIViewController *baseViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
while (baseViewController.presentedViewController && !baseViewController.presentedViewController.isBeingDismissed) {
baseViewController = baseViewController.presentedViewController;
}
[baseViewController presentViewController:alertController animated:YES completion:nil];
});
}
使い方の例
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:@"削除しますか?" preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:@"キャンセル" style:UIAlertActionStyleCancel handler:nil]];
__block __weak MyViewController *refSelf = self;
[alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[refSelf deleteLogic];
}]];
[Util showAlertController:alertController];
ActionSheet表示時のエラー対応
preferredStyleにUIAlertControllerStyleActionSheetを指定して表示しようとした際にこちらのエラーが出る場合。
NSGenericException', reason: 'Your application has presented a UIAlertController (<UIAlertController: 0x7b974060>) 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.'
以下の3点の指定をしましょう。
値は適宜置き換えてください。
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"アクションシートのタイトル" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
alertController.popoverPresentationController.sourceView = self.view;
alertController.popoverPresentationController.sourceRect = CGRectMake(self.view.bounds.size.width / 2, self.view.bounds.size.height /2, 1.0, 1.0);
alertController.popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionDown;
おわりに
調べたり対応するのに使った時間が、誰かの役に立ちますように。
参考になりましたら幸いです。