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!
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+
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!") } }
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
.
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