當您從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