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

I created a button, like the code below, but it will not respond in the log (presumably to show "ha"). The strangest part is that I was able to get this exact code to work inside the collection view, but usually not on the view controller. What am I doing wrong by clicking the "myAction" button?

-(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"); } 
+4
source share
2 answers

one)

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

2)

Change the management event from UIControlEventTouchUpInside to UIControlEventTouchDown

3)

The parent UIImageView may not have " userInteractionEnabled " set to true, which means that events will not be sent (or dispatched) to subviews.

To make these events available to subviews, change the parent view of the userInteractionEnabled property with:

 backImageView.userInteractionEnabled = YES; 

before adding this review.

+6
source

By default, the image userInteractionEnabled disabled. So you have to enable it with backImageView.userInteractionEnabled = YES;

+1
source

Source: https://habr.com/ru/post/1493064/


All Articles