3

我正在尝试在当前显示的视图控制器之上以模态方式显示 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 是否总是给出当前可见的视图控制器?

4

1 回答 1

2

如果您想做的UIWebView是在应用程序中显示的任何视图控制器的顶部显示模态,则不需要“最顶层”。获取根视图控制器就足够了。每当我想在其他所有内容之上呈现视图时,我都会一直这样做。您只需要引用库中的根视图控制器:

self.rootVC = [[[[UIApplication sharedApplication] delegate] window] rootViewController];

有了这个参考,你现在有两个选择:

第一个是使用UIViewController's 方法presentViewController:animated:completion:显示另一个 View Controller,它将包含您的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

如果您有任何其他问题,请告诉我。

希望这可以帮助!

于 2013-07-25T17:08:57.317 回答