Hi,
I am creating a view controller that will be used to enter text information.
The view itself consists of a label, text field and two buttons in the navigation bar: "cancel" and "OK".
When user presses "cancel" I am just popping back to the root view controller.
But when he presses OK, I want first to call a function from the root view controller and only after that to pop back.
I tried to implement it in the following way:
The header:
@interface UserInputViewController : UIViewController {
UILabel *textLabel;
UITextField *textField;
SEL OKButtonAction;
}
-(NSString*) getEnteredText;
-(UserInputViewController*) initWithTitle: (NSString*)title Text: (NSString*)text andOKButtonSelector: (SEL) OKButtonSelector;
@end
Implementation:
@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];
}
And here is the root view controller methods:
-(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];
}
But when I compile it and press the OK button from the pushed view, I get an exception.
I am not yet familiar with selectors programming, so I've got hard time trying to figure out what am I doing wrong.
How can I achieve this goal?
Thanks.