給View 添加手勢,點擊無反應 如何給View添加點擊事件,手勢方法


項目中有很多地方需要添加點擊事件,重復代碼很多,所以做了一個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;

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM