我正在尝试在当前显示的视图控制器之上模态显示UIWebview。弹出webview的代码存在于静态库中,并且不知道它所在的应用程序的视图控制器层次结构。下面的代码适用于我的测试用例,但不确定它是否适用于所有可能的视图控制器层次结构
UIViewController *rootViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];
UIViewController *presentedVC = [rootViewController presentedViewController];
if (presentedVC) {
// We have a modally displayed viewcontroller on top of rootViewController.
if (!presentedVC.isBeingPresented) {
[presentedVC presentViewController:vc animated:YES completion:^{
//
}];
} else {
rootViewController presentViewController:vc animated:YES completion:^{
//
}];
}
presentViewController是否总是提供当前可见的视图控制器?
答案 0 :(得分:2)
如果您想要做的是在应用程序中显示的View Controller之上以模态方式显示UIWebView
,则不需要“最顶层”。获取Root View Controller就足够了。每当我想在其他所有内容上呈现视图时,我会一直这样做。
您只需要引用库中的根视图控制器:
self.rootVC = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
有了这个参考,你现在有两个选择:
第一个是使用UIViewController
的方法presentViewController:animated:completion:
来显示另一个包含UIWebView
第二个选项是通过添加覆盖整个屏幕的子视图来伪造模态视图控制器,具有(半)透明背景,并包含要“模态”显示的视图。这是一个例子:
@interface FakeModalView : UIView // the *.h file
@property (nonatomic, retain) UIWebView *webView;
@property (nonatomic, retain) UIView *background; // this will cover the entire screen
-(void)show; // this will show the fake modal view
-(void)close; // this will close the fake modal view
@end
@interface FakeModalView () // the *.m file
@property (nonatomic, retain) UIViewController *rootVC;
@end
@implementation FakeViewController
@synthesize webView = _webView;
@synthesize background = _background;
@synthesize rootVC = _rootVC;
-(id)init {
self = [super init];
if (self) {
[self setBackgroundColor: [UIColor clearColor]];
_rootVC = self.rootVC = [[[[[UIApplication sharedApplication] delegate] window] rootViewController] retain];
self.frame = _rootVC.view.bounds; // to make this view the same size as the application
_background = [[UIView alloc] initWithFrame:self.bounds];
[_background setBackgroundColor:[UIColor blackColor]];
[_background setOpaque:NO];
[_background setAlpha:0.7]; // make the background semi-transparent
_webView = [[UIWebView alloc] initWithFrame:CGRectMake(THE_POSITION_YOU_WANT_IT_IN)];
[self addSubview:_background]; // add the background
[self addSubview:_webView]; // add the web view on top of it
}
return self;
}
-(void)dealloc { // remember to release everything
[_webView release];
[_background release];
[_rootVC release];
[super dealloc];
}
-(void)show {
[self.rootVC.view addSubview:self]; // show the fake modal view
}
-(void)close {
[self removeFromSuperview]; // hide the fake modal view
}
@end
如果您有任何其他问题,请告诉我。
希望这有帮助!