7

I'm trying to create a button, which once tapped will show a popover of another UIView. To test this out, I have the following code in my viewDidLoad section:

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.hard1 = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.hard1 setFrame:CGRectMake(884, 524, 105, 60)]; // set the x,y,width and height based on your specs
    UIImage *buttonImage = [UIImage imageNamed:@"green.jpg"];
    hard1.layer.cornerRadius = 10;
    hard1.clipsToBounds = YES;
    [hard1 addTarget: self
              action: @selector(buttonClicked:)
    forControlEvents: UIControlEventTouchUpInside];
    [self.hard1 setImage:buttonImage forState:UIControlStateNormal];
    [self.view addSubview:self.hard1];
}

and further down:

- (IBAction) buttonClicked: (id)sender
{
    NSLog(@"Tap");
}

however, the console does not log 'Tap' when I hit the button. Any ideas?

Louis Holley
  • 135
  • 1
  • 3
  • 10
  • [IOS 14 SDK: you can add action with closure callback:](https://stackoverflow.com/questions/5843427/how-do-you-add-an-action-to-a-button-programmatically-in-xcode/640871599#answer-64087159) – Ucdemir Sep 27 '20 at 10:02

3 Answers3

12

Watch these three lines of code:

hard1.layer.cornerRadius = 10;
hard1.clipsToBounds = YES;
[hard1 addTarget: self
          action: @selector(buttonClicked:)
forControlEvents: UIControlEventTouchUpInside];

You are missing self. in all three. They should be:

self.hard1.layer.cornerRadius = 10;
self.hard1.clipsToBounds = YES;
[self.hard1 addTarget: self
          action: @selector(buttonClicked:)
forControlEvents: UIControlEventTouchUpInside];

Also, if you are creating it programatically, it shouldn't be an IBAction (IB stands for interface builder and this is not created in interface builder).

Odrakir
  • 4,254
  • 1
  • 20
  • 52
  • 1
    Now that I'm on it. When you create a property do this in synthesize: @synthesize hard1 = _hard1; This way referring to the property as just "hard1" wont work. It's either self.hard1 or _hard1 (the latter only to be used in the setter method) – Odrakir Feb 24 '13 at 17:38
4
    self.hard1 = [UIButton buttonWithType:UIButtonTypeCustom];


 [hard1 addTarget: self
              action: @selector(buttonClicked:)    forControlEvents: UIControlEventTouchUpInside];

Replace hard1 to self.hard1

Kiran
  • 345
  • 1
  • 4
  • 16
0

You have put the event responder as buttonClicked but in IBAction you have defined buttonTap. This would obviously not work...

It should be

[hard1 addTarget: self
              action: @selector(buttonTap:)
    forControlEvents: UIControlEventTouchUpInside];
Srikar Appalaraju
  • 71,928
  • 54
  • 216
  • 264