How to create a UIButton programmatically in iOS 14 in objective-C?

2.4k Views Asked by At

I'm trying to create a UIButton programmatically in iOS 14 (beta 3) in objective-C. This is what I've tried, but the UIAction handler is never called when I tap the button:

UIAction *tapAction = [UIAction actionWithHandler:^(UIAction* action){
     NSLog(@"Never gets here");
}];
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100) primaryAction:tapAction];

Any ideas?

3

There are 3 best solutions below

0
On

I had the same issue. It looks like a bug to me. Try adding:

 self.contentView.isUserInteractionEnabled = true

to init(style:reuseIdentifier:) if you are using a custom tableview cell. Please refer to https://developer.apple.com/forums/thread/661508?page=1#636261022 and @OOPer great answer.

0
On

I wrote a test app that just displays a button and it's working, so the issue must be something else in my main app. Thanks all.

1
On

This is how I normally create a button in Objective-C:

- (void)createButton {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 50, 100);
    [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
}
    
- (void)buttonClicked:(UIButton *)sender {
   // Do your logic here
}

You can read more here: https://developer.apple.com/documentation/uikit/uicontrol/1618259-addtarget