penn-wang
一位老和尚,他身边聚拢着一帮虔诚的弟子。这一天,他嘱咐弟子每人去南山打一担柴回来。弟子们匆匆行至离山不远的河边,人人目瞪口呆。只见洪水从山上奔泻而下,无论如何也休想渡河打柴了。无功而返,弟子们都有些垂头丧气。唯独一个小和尚与师傅坦然相对。师傅问其故,小和尚从怀中掏出一个苹果,递给师傅说,过不了河,打不了柴,见河边有棵苹果树,我就顺手把树上唯一的一个苹果摘来了。后来,这位小和尚成了师傅的衣钵传人。

实现这个有很多方法,来看看我的小把戏。嘿嘿。

代码:

ClickImageView.h

@interface ClickImageView : UIImageView
{
    id _target;
    SEL _selector;
}

-(void)addTarget:(id)target selector:(SEL)selector;


@end

ClickImageView.m

#import "ClickImageView.h"

@implementation ClickImageView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
         self.userInteractionEnabled=YES;
    }
    return self;
}

-(id)initWithImage:(UIImage *)image
{
    self=[super initWithImage:image];
    if (self) {
        self.userInteractionEnabled=YES;
    }
    return self;
}

-(void)addTarget:(id)target selector:(SEL)selector
{
    _target=target;
    _selector=selector;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    if([_target respondsToSelector:_selector]){
        [_target performSelector:_selector withObject:self];
    }
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

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

@end

使用:

    imageView = [[ClickImageView alloc] initWithImage:image];
    [imageView addTarget:self selector:@selector(pressOnImageView:)];

 

posted on 2013-01-15 17:34  penn-wang  阅读(156)  评论(0编辑  收藏  举报