The Interface Builder method creates "freeze-dried" objects that are re-created at runtime when you initialize the object from the NIB. It still does the same alloc
and init
stuff, using NSCoder
objects to bring the objects in to memory.
If you want to have a view controller based on a particular NIB, you can then override the default init method and init it based on the NIB for that view controller. For example:
@implementation MyViewController
-(id) init {
if (self = [super initWithNibName:@"MyViewController" bundle:nil]) {
//other setup stuff
}
return self;
}
And when you want to display the MyViewController
, you would simply call something like this:
- (void) showMyViewController {
MyViewController *viewController = [[[MyViewController alloc] init] autorelease];
[self presentModalViewController:viewController animated:YES];
}
Now, if you want to create your view manually instead of in Interface Builder, you don't have to change your -showMyViewController
method at all. Get rid of your -init
override, and instead override the -loadView
method of your MyViewController
to create it programmatically:
- (void) loadView {
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(320,460)];
self.view = view;
[view release];
//Create a button
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[myButton addTarget:self action:@selector(pressedButton) forControlEvents:UIControlEventTouchUpInside];
[myButton setTitle:@"Push Me!" forState:UIControlStateNormal];
myButton.frame = CGRectMake(100,230,80,44);
[self.view addSubview:myButton];
}
This example shows how to create the view and add a button to it. If you want to keep a reference to it, declare it the same way you would if you were using a NIB (without the IBOutlet/IBActions) and use self
when assigning it. For example, your header might look like this:
@interface MyViewController : UIViewController {
UIButton *myButton;
}
- (void) pressedButton;
@property (nonatomic, retain) UIButton *myButton;
@end
And your class:
@implementation MyViewController
@synthesize myButton;
- (void) loadView {
//Create the view as above
self.myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[myButton addTarget:self action:@selector(pressedButton) forControlEvents:UIControlEventTouchUpInside];
[myButton setTitle:@"Push Me!" forState:UIControlStateNormal];
myButton.frame = CGRectMake(100,230,80,44);
[self.view addSubview:myButton];
}
- (void) pressedButton {
//Do something interesting here
[[[[UIAlertView alloc] initWithTitle:@"Button Pressed" message:@"You totally just pressed the button" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK",nil] autorelease] show];
}
- (void) dealloc {
[myButton release];
[super dealloc];
}