UIButton 的点击事件只能传递一个对象,即本身,不能传递另外的对象。一直想搞个传递两个对象的扩展。可是一直懒得写 ,最近做项目的时候遇到了 ,无奈只能搞定它先。本人用的是代理。添加一个成员属性 id 类型的 ,为什么是id呢。。哈哈 自己考虑去吧。。
下面直接上代码 。
//MyButton.h 文件
#import <UIKit/UIKit.h>
@class MyButton ;
@protocol MyButtonDelegate <NSObject>
@required
-(void) myButtonClick:(MyButton *) btn with:(id) obj ;
@end
@interface MyButton : UIButton
@property(nonatomic,strong) id obj ;
@property(nonatomic,weak) id<MyButtonDelegate> delegate ;
@end
MyButton.m 文件
#import "MyButton.h"
@implementation MyButton
- (instancetype)initWithFrame:(CGRect)frame {
if (self=[super initWithFrame:frame]) {
[self addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
}
return self ;
}
-(void)click:(UIButton *) button {
if ([self.delegate respondsToSelector:@selector(myButtonClick:with:)]) {
[self.delegate myButtonClick:self with:_obj];
}
}
在项目中使用的时候就不要再添加点击事件了。因为在init 中已经实现了。实现代理 直接使用就可以了 。。 轻喷