第一种方法:
UIWindow *window = [UIApplication sharedApplication].keyWindow;
UIViewController *rootViewController = window.rootViewController;
第二种方法:
AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
UIViewController *rootViewController1 = appdelegate.window.rootViewController;
建议获取rootViewController的时候还是采用
第二种方法:
AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
UIViewController *rootViewController1 = appdelegate.window.rootViewController;
其实,和alertView类似的,UIActionSheet也是这样的。
一般人说无所谓,但是如果在AlertView弹出的时候去获取RootViewController,并且对你认为获取正确的RootViewController做相关的操作,你会死的很惨。
建议:即使通过第二种方法获取到了RootViewController,在使用之前建议再判断一下获取到的类是不是就是自己想要的类型,更保险一些。
AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
if ([appdelegate.window.rootViewController isKindOfClass:["想要获取到的rootVC" class]] == YES) {
// 为所欲为
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。