如何在UIWindow中添加视图?

时间:2015-03-20 06:17:15

标签: ios objective-c uiwindow

我想在UIWindow中添加一个包含以下代码的视图:

 AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
 UIWindow *window = delegate.window;
 UIView *aView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
 aView.backgroundColor = [UIColor blackColor];
 [window addSubview:aView];

此代码无效。我想克隆UIAlertView的属性。当我们打电话时,它会弹出一切 [alertViewInstance show];方法。

也尝试过这个:

   UIView *aView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    UIWindow* window = [UIApplication sharedApplication].keyWindow;

    if (!window) {
        window = [[UIApplication sharedApplication].windows objectAtIndex:0];
    }

    [window addSubview:aView];
    [window bringSubviewToFront:aView];

8 个答案:

答案 0 :(得分:9)

如果您使用UINavigationController使用:

[self.navigationController.view.window addSubview:aView];

如果您使用UITabBarController使用:

[self.tabBarController.view.window addSubview:aView];

AppDelegate中,您可以直接为窗口指定视图。在appDelegate didFinishLaunchingWithOptions方法中使用:

[self.window addSubview:aView];

希望它有所帮助...

答案 1 :(得分:6)

试试这段代码:

window = [[UIApplication sharedApplication].windows lastObject];

替换以下代码:

window = [[UIApplication sharedApplication].windows objectAtIndex:0];

答案 2 :(得分:5)

尝试使用此代码:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    UIWindow* window = [UIApplication sharedApplication].keyWindow;
    if (!window) {
        window = [[UIApplication sharedApplication].windows objectAtIndex:0];
    }

    UIView *aView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    aView.backgroundColor = [UIColor redColor];
    aView.center = window.center;
    [window insertSubview:aView aboveSubview:self.view];
    [window bringSubviewToFront:aView];
}

答案 3 :(得分:4)

您的Windows需要有一个根视图控制器。

AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

UIWindow *window = delegate.window;
UIViewController *controller = [[UIViewController alloc] init]; 
window.rootViewController = controller;
UIView *aView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
aView.backgroundColor = [UIColor blackColor];
[controller.view addSubview:aView];

答案 4 :(得分:3)

您可以使用以下

添加视图
[[[UIApplication sharedApplication] keyWindow] addSubview:YOUR_VIEW];

答案 5 :(得分:2)

您可以尝试以下代码...将子视图添加到窗口

UIView *aView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
aView.backgroundColor = [UIColor blackColor];
[[UIApplication sharedApplication].keyWindow addSubview:aView];

//删除

[aView removeFromSuperview];

希望它可以帮助你......!

答案 6 :(得分:2)

我想你错过了这个。检查一次。

[self.window makeKeyAndVisible];

答案 7 :(得分:2)

当您调用show方法时,UIAlertView会创建另一个UIWindow并将此窗口设置为关键窗口。因此,如果要显示自己的警报视图,请创建一个UIWindow实例,并将其自定义警报视图添加到此新创建的窗口中。