-1

I am trying to add an action to a NSButton but it is not working

I create my NSButtton programmatically:

-(NSView *)rowTable:(CGFloat) heightOnPanel :(NSString *) textValue: (CGFloat) width: (CGFloat) height :(int) intColor{
    NSView *viewce = [[NSView alloc] initWithFrame:CGRectMake(0, heightOnPanel, 320, 40)];
    NSButton *layerBt = [[NSButton alloc] initWithFrame:NSMakeRect(0, 0, width, height)];

    [layerBt setTitle:textValue];

    [layerBt setButtonType:NSMomentaryPushInButton];
    [layerBt setTarget:nil];
    [layerBt setAction:@selector(buttonPressed:)];
    [viewce addSubview:layerBt];

    return viewce;
}

and here is IBAction method:

- (IBAction)buttonPressed:(id) sender{
    NSLog(@"hello world");
}

Could you point me to what I am missing?

Thanks

clemens
  • 16,716
  • 11
  • 50
  • 65
UIJoker
  • 19
  • 3
  • What's the question? – matt Apr 15 '18 at 13:05
  • You are aware that your `target` is `nil`, yes? So how do you imagine your `buttonPressed:` is going to be called? – matt Apr 15 '18 at 13:06
  • thank you matt - i am missing something this is why I asked here. No need to be rude – UIJoker Apr 15 '18 at 17:44
  • Not rudeness, I'm asking you what you think your code does. `nil` target, so when the button is pressed it sends the action message to _whom_? There _is_ such a thing as a `nil` targeted action, so perhaps you have a justification for expecting this to work. I am a rubber ducky: explain your code to me. – matt Apr 15 '18 at 19:27

1 Answers1

0

Your code should be valid if the object with the method buttonPressed: is a member of the responder chain. If it isn't you should set the target explicitly:

[layerBt setTarget:theTarget];
[layerBt setAction:@selector(buttonPressed:)];

where theTarget implements buttonPressed:.

clemens
  • 16,716
  • 11
  • 50
  • 65