UI target/action设计模式

target/action设计模式

MyView.h

@interface MyView : UIView
{
    //保存对象
    id _target;
    //保存方法
    SEL _action;
}
//给实例变量_target,_action赋值
- (void)addTarget:(id)target action:(SEL)action;
<p style="margin-top: 0px; margin-bottom: 0px; font-size: 18px; font-family: Menlo;"><pre name="code" class="objc">@property(nonatomic,retain) UIView *greenView;

@end
 
 
MyView.m

<pre name="code" class="objc">@implementation MyView

- (void)dealloc
{
    [_greenView release];
    [super dealloc];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        UIView *greenView=[[UIView alloc]initWithFrame:CGRectMake(40, 120, 100, 100)];
        greenView.backgroundColor=[UIColor greenColor];
        [self addSubview:greenView];
        [greenView release];
        self.greenView=greenView;
    }
    return self;
}

//给实例变量_target,_action赋值
- (void)addTarget:(id)target action:(SEL)action
{
    _target=target;
    _action=action;
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    //让_target对象执行_action方法,参数是nil
    [_target performSelector:_action withObject:self.greenView];

}
@end

 RootViewController.m 
 

@implementation RootViewController

-(void)loadView
{
    //在loadView中给self.view赋值,没有赋值之前self.view是空的。如果不重写loadView方法,则默认创建一个空白的view
    MyView *myView=[[MyView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
    myView.backgroundColor=[UIColor cyanColor];
    [myView addTarget:self action:@selector(changeColor:)];
    self.view=myView;
    [myView release];
}

- (void)changeColor:(UIView*)aView
{
    //改变颜色
    float red=arc4random()%256/255.0;
    float green=arc4random()%256/255.0;
    float blue=arc4random()%256/255.0;
    UIColor *randColor=[UIColor colorWithRed:red green:green blue:blue alpha:1];
    aView.backgroundColor=randColor;
}

@end







你可能感兴趣的:(UI target/action设计模式)