Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind Action to UIButton

Tags:

cocoa-touch

In my AppController I'm loading a View with the following code.

- (void) loadSettingsController {
    settingsViewController = [[SettingsViewController alloc] initWithNibName:@"SettingsView" bundle:nil];
    UIButton *button = settingsViewController.loginButton;
    [button addTarget:self action:@selector(saveSettings:) forControlEvents:UIControlEventTouchUpInside];
}

- (IBOutlet) saveSettings:(id) sender

The view is later on added to the window with the code

[window addSubview:[settingsViewController view]];

Everything works fine, but the action saveSettings doesn't get called when I press the button while using the debugger. The "loginButton" property is connected to the button in the Interface Builder.

Can you see anything wrong with this code?

like image 736
ullmark Avatar asked Feb 13 '09 12:02

ullmark


1 Answers

Change IBOutlet to IBAction

- (IBAction) saveSettings:(id) sender

It's because you try to acces your object before viewDidLoad got called. you must wait before viewDidLoad got called, there are numerous ways to achieve that.

add this to your SettingViewController viewDidLoad function

 [[NSNotificationCenter defaultCenter] postNotificationName:@"SettingsViewDidLoad" object:nil];

and this to your the ViewController you want to access the button

- (void) loadSettingsController {
       settingsViewController = [[SettingsViewController alloc] initWithNibName:@"SettingsView" bundle:nil];
       [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initControls) name:@"SettingsViewDidLoad" object:nil];
}

-(void)initControls{
       UIButton *button = settingsViewController.loginButton;
       [button addTarget:self action:@selector(saveSettings:) forControlEvents:UIControlEventTouchUpInside];
}
like image 89
Andy Jacobs Avatar answered Jan 02 '23 22:01

Andy Jacobs