【发布时间】:2019-01-28 22:15:49
【问题描述】:
我正在将一些自 iOS 9.0 以来已弃用的 UIAlertViews 更新为 UIAlertViewControllers。
使用 UIAlertView,可以从任何正在执行的代码中抛出警报——即使是在实用程序类或共享实例中——只需一行:
[alertView show];
所以如果我调用一个共享实例,比如
- (void)didTapDeleteButton:(id)sender {
NSArray *itemsToDelete = [self.selectedIndexPathToContact allValues];
[[IDModel sharedInstance] deleteItems:itemsToDelete];
//其中包含代码:
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Keep Archive Copy?"
message:nil
delegate:self
cancelButtonTitle:@"No"
otherButtonTitles:@"OK",nil];
alertInvite.alertViewStyle = UIAlertViewStyleDefault;
alertInvite.tag=100;
[alertView show];
一切正常。
但是,对于 UIAlertController,这是不允许的。如果将以下代码放在通过共享实例可访问的类的方法中,当您到达 presentViewController 时,会抛出错误:
UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"Delete Item?" message:nil preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* yesButton = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
[alertView dismissViewControllerAnimated:YES completion:nil];
}];
UIAlertAction* noButton = [UIAlertAction actionWithTitle:@"Not Now" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
[alertView dismissViewControllerAnimated:YES completion:nil];
}];
[alertView addAction:noButton];
[alertView addAction:yesButton];
if ([alertView respondsToSelector:@selector(setPreferredAction:)]) {
[alertView setPreferredAction:yesButton];
}
//FOLLOWING THROWS ERROR
[self presentViewController:alertView animated:YES completion:nil];
在最后一行,类(通过共享实例访问)没有此方法。看来您必须使用更复杂的方式来引发警报。我见过一些somwehat convoluted approaches,例如:
id rootViewController = [UIApplication sharedApplication].delegate.window.rootViewController;
if([rootViewController isKindOfClass:[UINavigationController class]])
{
rootViewController = ((UINavigationController *)rootViewController).viewControllers.firstObject;
}
if([rootViewController isKindOfClass:[UITabBarController class]])
{
rootViewController = ((UITabBarController *)rootViewController).selectedViewController;
}
[rootViewController presentViewController:alertInvite animated:YES completion:nil];
但是,这对我不起作用,因为我认为我的共享实例没有 rootviewcontroller。谁能提出一个简单直接的方法来做到这一点?
【问题讨论】:
-
你指的是什么sharedInstance? Edit您的问题(没有 cmets),在您需要致电
[self presentViewController...的地方有更多的上下文。 -
selfin[self presentViewController必须是UIViewController -
他说 sharedInstance 没有 present 方法,所以我推断它是任何随机的 NSObject 而不是 VC
-
查看@rmaddy 要求的其他代码
-
是的,sharedInstance是一个NSObject
标签: ios objective-c uialertviewcontroller