static char * const UIViewBlockKey = "UIHelperViewBlockKey";
@implementation UIView (UIHelper)
+ (UIView *) viewWithtouchesBegan:( void(^)(NSSet *touches, UIEvent *event) ) touchesBeganBlock
touchesMoved:( void(^)(NSSet *touches, UIEvent *event) ) touchesMovedBlock
touchesEnded:( void(^)(NSSet *touches, UIEvent *event) ) touchesEndedBlock
touchesCancelled:( void(^)(NSSet *touches, UIEvent *event) ) touchesCancelledBlock
{
UIView *theView = [[UIView alloc] init];
NSArray *opreations = (NSArray *)objc_getAssociatedObject(theView, UIViewBlockKey);
if (opreations == nil)
{
opreations = [[NSArray arrayWithObjects:touchesBeganBlock, touchesMovedBlock, touchesEndedBlock, touchesCancelledBlock, nil] retain];
objc_setAssociatedObject(theView, UIViewBlockKey, opreations, OBJC_ASSOCIATION_RETAIN);
}
return [theView autorelease];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSArray *opreations = (NSArray *)objc_getAssociatedObject(self, UIViewBlockKey);
void(^handle)(NSSet *touches, UIEvent *event) = [opreations objectAtIndex:0];
if (handle == nil)
{
return;
}
handle(touches, event);
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
NSArray *opreations = (NSArray *)objc_getAssociatedObject(self, UIViewBlockKey);
void(^handle)(NSSet *touches, UIEvent *event) = [opreations objectAtIndex:1];
if (handle == nil)
{
return;
}
handle(touches, event);
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
NSArray *opreations = (NSArray *)objc_getAssociatedObject(self, UIViewBlockKey);
void(^handle)(NSSet *touches, UIEvent *event) = [opreations objectAtIndex:2];
if (handle == nil)
{
return;
}
handle(touches, event);
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
NSArray *opreations = (NSArray *)objc_getAssociatedObject(self, UIViewBlockKey);
void(^handle)(NSSet *touches, UIEvent *event) = [opreations objectAtIndex:3];
if (handle == nil)
{
return;
}
handle(touches, event);
}
@end
//使用方法***************
UIView *aView = [UIView viewWithtouchesBegan:^(NSSet *touches, UIEvent *event) {
NSLog(@"touchesBegan");
} touchesMoved:^(NSSet *touches, UIEvent *event) {
NSLog(@"touchesMoved");
} touchesEnded:^(NSSet *touches, UIEvent *event) {
NSLog(@"touchesEnded");
} touchesCancelled:^(NSSet *touches, UIEvent *event) {
NSLog(@"touchesCancelled");
}];
aView.frame = CGRectMake(100, 0, 100, 44);
aView.backgroundColor = [UIColor redColor];
[self.window addSubview:aView];