创建一个TargetActionView类
@interface TargetActionView : UIView
@property(nonatomic,assign)id target; //定义属性
@property(nonatomic,assign) SEL action;
-(id)initWithFrame:(CGRect)frame target:(id)target action:(SEL)action;//初始化方法
@end
实现
#import "TargetActionView.h"
@implementation TargetActionView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
-(id)initWithFrame:(CGRect)frame target:(id)target action:(SEL)action
{
self=[super initWithFrame:frame];
if (self) {
_target=target;
_action=action;
}
return self;
}
//touchesBegan方法
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[_target performSelector:_action withObject:self];
}
主函数
TargetActionView *targetActionView=[[TargetActionView alloc]initWithFrame:CGRectMake(30, 30, 130, 130) target:self action:@selector(changColor:)];
targetActionView.backgroundColor=[UIColor redColor];
[self.view addSubview:targetActionView];
// Do any additional setup after loading the view.
}
-(void)changColor:(TargetActionView *)color
{
color.backgroundColor=[UIColor orangeColor];
}