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
PopupViewController.h
#import <UIKit/UIKit.h>
@class PopupViewController;
@protocol PopupViewControllerDelegate
- (void)viewController:(PopupViewController *)controller viewTapped:(UIView *)view;
@end
@interface PopupViewController : UIViewController
@property (nonatomic, assign) NSObject<PopupViewControllerDelegate> *delegate;
- (IBAction)viewTapped:(UIView *)view;
@end
Then in your implementation
PopupViewController.m
- (IBAction)viewTapped:(UIView *)view {
if (!self.delegate) return;
if ([self.delegate respondsToSelector:@selector(viewController:viewTapped:)]) {
[self.delegate viewController:self viewTapped:view];
}
}
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.
本文介绍了一种通过设置代理协议来安全地响应按钮点击事件的方法,避免了直接使用addTarget导致的目标对象被释放后发送消息的风险。
1836

被折叠的 条评论
为什么被折叠?



