UIButton set touch handler in code

本文介绍了一种通过设置代理协议来安全地响应按钮点击事件的方法,避免了直接使用addTarget导致的目标对象被释放后发送消息的风险。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值