Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

uibutton

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");
}
like image 354
user2495313 Avatar asked Mar 23 '23 02:03

user2495313


1 Answers

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.

like image 171
Michael Dautermann Avatar answered Apr 09 '23 00:04

Michael Dautermann