当您从NIB初始化对象时,Interface Builder方法会创建在运行时重新创建的“冻干”对象。它仍然使用相同的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];
}
谢谢你,这是非常有帮助的。 – vickirk 2009-10-23 14:13:02