如何在UIWindow中添加视图?

Pra*_*tha 9 objective-c uiwindow ios

我想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];
Run Code Online (Sandbox Code Playgroud)

这段代码不起作用.我想克隆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];
Run Code Online (Sandbox Code Playgroud)

Vis*_*l16 10

如果您UINavigationController使用的是:

[self.navigationController.view.window addSubview:aView];
Run Code Online (Sandbox Code Playgroud)

如果您UITabBarController使用的是:

[self.tabBarController.view.window addSubview:aView];
Run Code Online (Sandbox Code Playgroud)

AppDelegate您可以直接将视图分配给窗口.在appDelegate didFinishLaunchingWithOptions方法中使用:

[self.window addSubview:aView];
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你...


小智 6

试试这段代码:

window = [[UIApplication sharedApplication].windows lastObject];
Run Code Online (Sandbox Code Playgroud)

替换以下代码:

window = [[UIApplication sharedApplication].windows objectAtIndex:0];
Run Code Online (Sandbox Code Playgroud)


Tie*_*nLe 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];
}
Run Code Online (Sandbox Code Playgroud)


Nik*_* M. 4

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

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];
Run Code Online (Sandbox Code Playgroud)