我正在創建一個視圖控制器,用於輸入文本信息。iPhone編程中的選擇器
視圖本身由導航欄中的標籤,文本字段和兩個按鈕組成:「取消」和「確定」。
當用戶按下「取消」時,我只是彈出回到根視圖控制器。
但是,當他按下OK時,我想首先從根視圖控制器調用一個函數,然後才彈出。
我試圖實現它以下列方式:
標題:
@interface UserInputViewController : UIViewController {
UILabel *textLabel;
UITextField *textField;
SEL OKButtonAction;
}
-(NSString*) getEnteredText;
-(UserInputViewController*) initWithTitle: (NSString*)title Text: (NSString*)text andOKButtonSelector: (SEL) OKButtonSelector;
@end
實現:
@implementation UserInputViewController
-(UserInputViewController*) initWithTitle: (NSString*)title Text: (NSString*)text andOKButtonSelector: (SEL) OKButtonSelector
{
self = [self init];
self.title = title;
OKButtonAction = OKButtonSelector;
textLabel = [ [UILabel alloc] initWithFrame: CGRectMake(20, 20, 280, 50)];
[textLabel setText: text];
[ [self view] addSubview: textLabel];
textField = [ [UITextField alloc] initWithFrame: CGRectMake(20, 100, 280, 50)];
[ [self view] addSubview: textField];
return self;
}
-(NSString*) getEnteredText
{
return [textField text];
}
-(void) popToRootViewController
{
[ [self navigationController] popToRootViewControllerAnimated: YES ];
}
-(void) popToRootWithOKAction
{
[ [self navigationController] popToRootViewControllerAnimated: YES ];
[self performSelector: OKButtonAction];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
//Cancel button
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle: NSLocalizedString(@"cancel button", @"") style: UIBarButtonSystemItemCancel target: self action: @selector(popToRootViewController) ];
[ [self navigationItem] setLeftBarButtonItem: cancelButton animated: NO];
[cancelButton release];
//OK button
UIBarButtonItem *OKButton = [[UIBarButtonItem alloc] initWithTitle: NSLocalizedString(@"ok button", @"") style: UIBarButtonSystemItemSave target: self action: @selector(popToRootWithOKAction) ];
[ [self navigationItem] setRightBarButtonItem: OKButton animated: NO];
[OKButton release];
}
這裏是根視圖控制器方法:
-(void) OKButtonAction
{
NSLog(@"text: %@", [newProfileDialog getEnteredText]);
[newProfileDialog release];
}
-(void) add_clicked {
newProfileDialog = [ [UserInputViewController alloc] initWithTitle: @"User name" Text: @"Please enter a new user name:" andOKButtonSelector: @selector(OKButtonAction)];
[ [self navigationController] pushViewController: newProfileDialog animated: YES];
}
但是,當我編譯它並從推送的視圖中按確定按鈕時,我收到一個異常。
我還不熟悉選擇器編程,所以我很難找出我做錯了什麼。
我該如何實現這個目標?
謝謝。