Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addSubview not working

// Create and add a sub view
CGRect viewRect = CGRectMake(0, 0, 200, 200);
UIView *a_sub_view = [[UIView alloc] initWithFrame : viewRect];

[window addSubview : a_sub_view];

After adding the above 3 lines of code, xcode produces no errors or warnings. But the sub-view is not showing at all. The sample program seems to be running exactly as before. Hope that somebody knowledgable could help.

like image 491
Stanley Avatar asked Jun 19 '11 15:06

Stanley


3 Answers

I find it useful to set the background color so I know where the view is and the boundaries.

a_sub_view.backgroundColor = [UIColor redColor];

In your example, you're create an empty view so you won't 'see' anything.

like image 109
bbarnhart Avatar answered Nov 01 '22 15:11

bbarnhart


window expects a viewcontrollers view to be added.

you can then add subviews to the current view.

so in your example use:

[self.view addSubview:a_sub_view];
like image 29
Nik Burns Avatar answered Nov 01 '22 13:11

Nik Burns


I am using this in order to "find" the window:

UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
[window addSubview:myView];

This also worked for me, but it is a bit uglier:

[self.navigationController.tabBarController.view addSubview:myView];

To explain the second one, I had to "follow" the controllers back up to the "top" view. (My application has a tab bar with a navigation controller inside the current tab.)

like image 41
MikecheckDev Avatar answered Nov 01 '22 13:11

MikecheckDev