Interface Builder 方法创建“冻干”对象,当您从 NIB 初始化对象时,这些对象会在运行时重新创建。它仍然使用 alloc 和 init 相同的东西,使用 NSCoder 对象将对象带入内存。
如果您想拥有一个基于特定 NIB 的视图控制器,您可以覆盖默认的 init 方法并根据该视图控制器的 NIB 对其进行初始化。例如:
@implementation MyViewController
-(id) init {
if (self = [super initWithNibName:@"MyViewController" bundle:nil]) {
//other setup stuff
}
return self;
}
当你想显示MyViewController时,你可以简单地调用这样的东西:
- (void) showMyViewController {
MyViewController *viewController = [[[MyViewController alloc] init] autorelease];
[self presentModalViewController:viewController animated:YES];
}
现在,如果您想手动创建视图而不是在 Interface Builder 中创建视图,则根本不必更改 -showMyViewController 方法。摆脱你的 -init 覆盖,而是覆盖你的 MyViewController 的 -loadView 方法以编程方式创建它:
- (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];
}
这个例子展示了如何创建视图并向其添加按钮。如果您想保留对它的引用,请以与使用 NIB(没有 IBOutlet/IBActions)相同的方式声明它,并在分配时使用 self。例如,您的标题可能如下所示:
@interface MyViewController : UIViewController {
UIButton *myButton;
}
- (void) pressedButton;
@property (nonatomic, retain) UIButton *myButton;
@end
还有你的班级:
@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];
}