Programmatically creating Views in IOS (how does it work)?

You need to have a view (or window) to add a subview to. The normal syntax is like this:

UIView *newView = [[UIView alloc] initWithFrame:mainView.bounds];
[mainView addSubview:newView];
[newView release];

Of course, if you have a custom object that inherits from UIView, you would use that instead of UIView. When you start a new project, create a "View based application", that will start you off with a view controller with an associated view (which can be accessed with "CustomViewController.view", which would replace "mainView" in the code snippet above).

If you want to create the view programmatically when the app starts, put the code in the "- (void)viewDidLoad" method of your view controller.


This is an old question, but I'm not sure he got the answer he expected - it sounds like he ran into the same problem I did where I created a UIViewController subclass, whacked a UIViewController in an interface builder nib but then couldn't figure out how to get the two working with one another.

If you made the nib seperately (so it wasn't made for you alongside your class) then you have to remember to click the UIViewController you placed in the interface builder, and then from the properties panel click the third tab button ('Custom Class'). The Class will be the default base class UIViewController etc - just open up this dropdown list and you'll see a list of all your custom subclasses, select it and volla - you've linked your custom element to the interface.

Hope that saves somebody the days it took me to figure out, I found some stupidly wonderful ways of getting around it until I realized the simple solution.


To be even more specific to your question, the syntax would be

UIWindow* window = [UIApplication sharedApplication].keyWindow;

UIView *polygonView = [[UIView alloc] initWithFrame: CGRectMake ( 0, 0, 200, 150)];
//add code to customize, e.g. polygonView.backgroundColor = [UIColor blackColor];

[window addSubview:polygonView];
[polygonView release];

This is a pattern you will use for not only this but subviews afterwards. Also, another note is with many of the templates, the viewController is already set up with it's own view. When you want to make a custom view, you create it like above but instead of the method above you set the viewControllers view to the newly created view like so:

viewController.view = polygonView;

Good luck!