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");
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With