user2495313
user2495313

Reputation: 91

Programmatically created a button on iOS, but no action when pressed

I created a button just like the code below, but it will not respond in the log (supposed to show "ha"). The strangest part is that I have been able to get this exact code to work inside a collection view, but not normally on a viewcontroller. What am I doing wrong with the button press "myAction"?

-(void)viewDidLoad {
    UIButton *buttonz = [UIButton buttonWithType:UIButtonTypeCustom];
        buttonz.frame = CGRectMake(160, 0, 160, 30);
        [buttonz setTitle:@"Charge" forState:UIControlStateNormal];
        [buttonz addTarget:self action:@selector(myAction:) forControlEvents:UIControlEventTouchUpInside];
        [buttonz setEnabled:YES];

        [buttonz setBackgroundColor:[UIColor blueColor]];

        //add the button to the view
        [backImageView addSubview:buttonz];
}

-(void)myAction:(id)sender {
NSLog(@"ha");
    [self resignFirstResponder];
    NSLog(@"ha");
}

Upvotes: 4

Views: 6494

Answers (2)

Dhaval Parmar
Dhaval Parmar

Reputation: 46

By default image userInteractionEnabled is disable. So, you have to enable it by backImageView.userInteractionEnabled = YES;

Upvotes: 1

Michael Dautermann
Michael Dautermann

Reputation: 89509

1)

You don't need to "resignFirstResponder" on a button (seems like most of the time I see "resignFirstResponder" is in text fields or text views).

2)

Change the control event from UIControlEventTouchUpInside to UIControlEventTouchDown

3)

The parent UIImageView might not have "userInteractionEnabled" set to true, which means events won't be propogated (or sent along) to subviews.

To make those events available to subviews, change the parent view's userInteractionEnabled property via:

backImageView.userInteractionEnabled = YES;

before adding that subview.

Upvotes: 6

Related Questions