大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请多提意见,如果觉得不错请多多支持点赞.谢谢! hopy ;)
以前我们可以在任何类中使用UIAlertView的show实例方法显示消息框
但是自从废弃了UIAlertView之后,作为替代我们可以使用心得消息框弹出方法UIAlertController来显示,但是该对象只能通过ViewController的presentViewController:alert animated:YES completion:方法来显示.
那么如何在其他类中使用UIAlertController显示消息框呢?
其实很简单,我们可以通过Application的window对象定位到任何我们希望的UIViewController,从而显示消息框,示例代码如下:
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Reversed" message: msgString preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"OK" style: UIAlertActionStyleCancel handler:^(UIAlertAction *action){ [self activityDidFinish:YES]; }]; [alert addAction:cancelAction]; UIViewController *vc = [UIApplication sharedApplication].windows[0].rootViewController; [vc presentViewController:alert animated:YES completion:nil];
通过以上代码,可以看到我们是如何取得App中的ViewController对象的.