Reputation: 199
I found some answers to my question but it still does not work. I have setup a button in IB and I want to setup the action and target by code(just for learning). I have a function in my MainViewController:
- (IBAction) onSpecialCase:(id)sender {
NSLog(@"It's working");
}
In the viewDidLoad function I do this:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
[myButton setTarget:self];
[myButton setAction:@selector(onSpecialCase:)];
}
Xcode already marks these lines telling me: "UIButton may not respond to 'setTarget'". When running the app anyways it terminates saying:
-[UIRoundedRectButton setTarget:]: unrecognized selector sent to instance 0x4b47e30
2011-06-29 08:12:22.465 FirstTry[3765:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIRoundedRectButton setTarget:]: unrecognized selector sent to instance 0x4b47e30'
That's what I could expect from the XCode warning, but why is that? Every example I find on the web is exactly like mine. Adding the actionMethode to the button via IB works like expected. What am I doing wrong?
Upvotes: 2
Views: 6012
Reputation: 1938
first check if you have declared the button as an outlet, second you should check if you connect the outlet to the button or use what I usually do is to add new button in code
UIButton *Button=[UIButton buttonWithType:UIButtonTypeCustom] ;
Button.frame=CGRectMake(0,0,30,30); // place your button
[Button addTarget:self action:@selector(processButtonCLick) forControlEvents:UIControlEventTouchUpInside];
[Button setImage:[UIImage imageNamed:@"imageoricon.png"] forState:UIControlStateNormal];
[self.view addSubview:Button];
Upvotes: 9
Reputation: 5540
It may help you.
UIButton *sendButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[sendButton setTitle:@"Send" forState:UIControlStateNormal];
[sendButton.titleLabel setFont:[UIFont boldSystemFontOfSize:12]];
sendButton.frame = CGRectMake(0, 3, 67, 37);
[sendButton addTarget:self action:@selector(sendButtonClicked) forControlEvents:UIControlEventTouchUpInside];
Upvotes: 2