0

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?

  • Possible duplicate [How do I create a basic UIButton programmatically?](https://stackoverflow.com/questions/1378765/how-do-i-create-a-basic-uibutton-programmatically) – MadProgrammer Aug 05 '20 at 00:39
  • This is not a duplicate. My old code using addTarget doesn't work on iOS 14. The target is never called. My understanding is that iOS 14 changes the way the target is specified by requiring a UIAction. – krause5612 Aug 05 '20 at 15:44
  • To clarify, I am using Xcode 12 beta 3. – krause5612 Aug 05 '20 at 17:14
  • macOS Big Sur 11.0 beta, Xcode 12.0 beta 4, iOS 14.0 beta 3 - based on the code from the linked duplicate - works fine for me - your problem is somewhere else – MadProgrammer Aug 05 '20 at 23:43
  • Yes, I figured out that the issue is caused by the fact that the button was inside a table view cell. Prior to iOS 14, the target is called, but on iOS 14, it is not. As a workaround, I use didSelectRowAtIndexPath and find the button in the cell and call the target directly. – krause5612 Aug 07 '20 at 16:42

3 Answers3

1

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.

Klo
  • 145
  • 8
0

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

knutigro
  • 1,082
  • 2
  • 10
  • 20
0

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.