target:action使用

創建一個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];
}





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章