I have gone through quite a few hello world tutorials for the iPhone, and they always reach the point of saying ' and now some magic occurs. You don't need to worry about this... the .XIB takes care of it '
I don't like this. what if I have a project where I am not going to be using IB? it don't want a large invisible object doing unknown things to my code. that makes me feel uneasy.
So, here is a step-by-step Guide to getting a pure code application template. I am using Xcode 3 -- it should be pretty similar for other versions.
- create new project -> view based application "NoXIB"
- delete both .xib files
- open Info.plist, locate the key: "Main nib file base name:" and delete "MainWindow"
- fiddle main.m
#import <UIKit/UIKit.h>
int main(int argc, char *argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, @"noXIBAppDelegate");
[pool release];
return retVal;
}
- can remove the IBOutlet from here:
#import <UIKit/UIKit.h>
@class noXIBViewController;
@interface noXIBAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
noXIBViewController *viewController;
}
@property (nonatomic, retain) UIWindow *window;
@property (nonatomic, retain) noXIBViewController *viewController;
@end
- create the window and the view controller here:
#import "noXIBAppDelegate.h"
#import "noXIBViewController.h"
@implementation noXIBAppDelegate
@synthesize window;
@synthesize viewController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];;
self.viewController = [[[noXIBViewController alloc] init] autorelease];
[window addSubview:viewController.view];
[window makeKeyAndVisible];
return YES;
}
- create a view; groups and files pane, right click on NoXIB -> 'classes', add new file, "MyView".
- make sure it is a subclass of UIView.
- override its drawRect so that it draws a red rectangle:
#import "MyView.h"
@implementation MyView
:
- (void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextClearRect(ctx, rect);
CGContextSetRGBFillColor(ctx, 255, 0, 0, 1);
CGContextFillRect(ctx, CGRectMake(10, 10, 50, 50));
}
- make the view controller load this view
#import "noXIBViewController.h"
#import "MyView.h"
@implementation noXIBViewController
- (void)loadView {
[super loadView];
CGRect frame = CGRectMake(10, 10, 300, 300);
MyView* myV = [ [ [MyView alloc] initWithFrame:frame] autorelease];
myV.clipsToBounds = YES;
[[self view] addSubview: myV];
}
:
:
Bingo! No XIB!