項目中有很多地方需要添加點擊事件,重復代碼很多,所以做了一個UIView的分類,專門做點擊事件使用.
項目地址:UIView-Tap
代碼很簡單,主要有一點就是注意分類不能直接添加屬性,需要用到運行時相關內容.
代碼如下:
\\UIView+Tap.h文件 @interface UIView (Tap) - (void)addTapBlock:(void(^)(id obj))tapAction; @end \\UIView+Tap.m文件 #import <objc/runtime.h> static const void* tagValue = &tagValue; @interface UIView () @property (nonatomic, copy) void(^tapAction)(id); @end @implementation UIView (Tap) - (void)tap{ if (self.tapAction) { self.tapAction(self); } } - (void)addTapBlock:(void(^)(id obj))tapAction{ self.tapAction = tapAction; if (![self gestureRecognizers]) { self.userInteractionEnabled = YES; UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)]; [self addGestureRecognizer:tap]; } } -(void)setTapAction:(void (^)(id))tapAction { objc_setAssociatedObject(self, tagValue, tapAction, OBJC_ASSOCIATION_COPY_NONATOMIC); } -(void (^)(id))tapAction { return objc_getAssociatedObject(self, tagValue); } @end
正如大家所見,如果要接收點擊事件,必須userInteractionEnabled設置為YES,所以不管怎么只要確認要給視圖添加點擊事件,都會被設置為userInteractionEnabled = YES
簡單實用:
\\UIView+Tap.h文件
UIView *redView = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)]; redView.backgroundColor = [UIColor redColor]; [redView addTapBlock:^(UIView* obj) { NSLog(@"redView%@",obj.backgroundColor); }]; [self.view addSubview:redView]; UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 250, 100, 100)]; imageView.image = [UIImage imageNamed:@"icon"]; [imageView addTapBlock:^(UIImageView* obj) { NSLog(@"imageView:\n%@",obj.image); }]; [self.view addSubview:imageView]; UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(150, 400, 100, 100)]; label.text = @"這是label,點擊這里..."; [label addTapBlock:^(UILabel* obj) { NSLog(@"label:\n%@",obj.text); }]; [self.view addSubview:label];
有時候需要做出響應 比如在cell中 沖突
//-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
//
// if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
// return NO;
// }
// return YES;
//
//}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
// 過濾掉UIButton,也可以是其他類型
if ( [touch.view isKindOfClass:[UIView class]])
{
return NO;
}
return YES;
}
