Create the Sub View

Create a view as normal

Menu > File > New File > iOS > Cocao Touch > UIViewControllerSubClass
Subclass of > UIViewController
With XIB for user interface = Checked
Name it (“#ViewController”, ending with “_iPhone” and “_iPad” for multi device apps, is a good naming convention)

In interface builder select the view and in the simulated metrics properties set the 3 bar options to none so taht you can change the views size.  Then set the views width and height as required

Add the objects you want in the view

Adding The Sub View To A View Controller Programatically

Import the view
#import "#ViewController.h"
Add The Sub View

//********** VIEW WILL APPEAR **********
- (void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];

	//Add sub view
	#ViewController *vc1 = [[#ViewController alloc] init];
	[self.view addSubview:vc1.view];
	vc1.view.frame = CGRectMake(0, 100, 320, 160);   //Set the sub view position within this main view
}

As Mike mentions in the comments viewDidLoad is actually often a better place for loading a sub view.

Setting Up Sub View Objects

Create a function in the subview to call.
In #ViewController.h

- (void)setupThisSubView:(NSString *) labelText;

In #ViewController.m


//********** SETUP THIS SUB VIEW **********
- (void)setupThisSubView:(NSString *) labelText
{
    [lblTitle setText:labelText];

}

Comments

  1. Mike Amaral

    You almost never want to add a view as a subview in viewWillAppear, because viewWillAppear can be called multiple times in the life cycle of a view controller. viewDidLoad is a much better place for this.