Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton set touch handler in code

I want to accomplish touching a UIButton and having code run in a different class than the owner.

I realize I can do a touchUpInside to the button's owner (ClassA) and then call the method inside ClassB that I want called, but is there any way to expedite this?

ideas:

  • have ClassB be the delegate for the ClassA->UIButton

  • set the touchUpInside call in programming to used the function inside ClassB

I'm not sure how to accomplish either of these ideas :( Input is mas appreciated!

like image 454
Jacksonkr Avatar asked Oct 30 '11 17:10

Jacksonkr


People also ask

What is UIButton in xcode?

A control that executes your custom code in response to user interactions. iOS 2.0+ iPadOS 2.0+ Mac Catalyst 13.1+ tvOS 9.0+

How do I add a target to a button in swift 5?

Using a UIControl with a closure callback viewDidLoad() let button = UIButton(type: . system) button. addTarget(self, action: #selector(buttonTapped(_:)), for: . touchUpInside) } @IBAction func buttonTapped(_ sender: UIButton) { print("Button tapped!") } }


1 Answers

One option is to set the button up using

[myButton addTarget:yourOtherClass action:@selector(mySelector:) forControlEvents:UIControlEventTouchUpInside];

but this is a bit dangerous because target is not retained so you could send the message to a deallocated object.

You could instead set up a protocol

MyController.h

@protocol MyControllerDelegate
- (void)myController:(MyController *)controller buttonTapped:(UIButton *)button;
@end

@interface MyController : UIViewController

@property (nonatomic, assign) id <MyControllerDelegate> delegate;

- (IBAction)buttonTapped:(UIButton *)button;

@end

Then in your implementation

MyController.m

- (IBAction)buttonTapped:(UIButton *)button
{
    if ([self.delegate respondsToSelector:@selector(myController:buttonTapped:)]) {
      [self.delegate myController:self buttonTapped:button];
    }
}

As the method defined in the protocol was not optional I could have instead done a check for (self.delegate) to make sure it is set instead of respondsToSelector.

like image 176
Paul.s Avatar answered Sep 22 '22 18:09

Paul.s