Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically code UIButton action

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?

like image 208
Louis Holley Avatar asked Feb 24 '13 17:02

Louis Holley


People also ask

How do I give a constraint to button programmatically in Swift?

Add the button in the view, give it constraints and as you are using constraints, you can skip the button. frame and add widthAnchor and heightAnchor . At last activate them and keep translatesAutoresizingMaskIntoConstraints as false . Also, it will be better if you can add proper names.

What is UIButton Swift?

A control that executes your custom code in response to user interactions.


2 Answers

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).

like image 171
Odrakir Avatar answered Oct 15 '22 09:10

Odrakir


    self.hard1 = [UIButton buttonWithType:UIButtonTypeCustom];


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

Replace hard1 to self.hard1

like image 36
Kiran Avatar answered Oct 15 '22 08:10

Kiran