iOS开发 - 为View添加Block回调(包含单击手势)

2018-04-12  本文已影响0人  阿唯不知道
创建一个UIView的类别

#import "UIView+YSAddClickBlock.h 文件"

#import <UIKit/UIKit.h>

@interface UIView (YSAddClickBlock)
- (void)addClickEventBlock:(void (^)(id obj))aBlock;
@end

#import "UIView+YSAddClickBlock.m 文件"

#import "UIView+YSAddClickBlock.h"

static const void *YSUIViewBlockKey = &YSUIViewBlockKey;
@interface UIView ()

@property void(^clickBlock)(id);

@end


@implementation UIView (YSAddClickBlock)

- (void)setClickBlock:(void (^)(id))clickBlock {
    objc_setAssociatedObject(self, YSUIViewBlockKey, clickBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (void (^)(id))clickBlock{
    return objc_getAssociatedObject(self, YSUIViewBlockKey);
}

- (void)addClickEventBlock:(void (^)(id obj))aBlock {
    self.clickBlock = aBlock;
    if (![self gestureRecognizers]) {
        self.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(blockAction)];
        [self addGestureRecognizer:tap];
    }
}

- (void)blockAction {
    if (self.clickBlock) {
        self.clickBlock(self);
    }
}

@end

调用方式(引用#import "UIView+YSAddClickBlock.h后)

    UIView *view = [[UIView alloc] init];
    view.backgroundColor = kRandomColor;
    [view addClickEventBlock:^(id obj) {
        [self showMessageHud:@"我是UIView的手势Block回调"];
        ((UIView *) obj).backgroundColor = kRandomColor;
    }];
    [self.view addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(label.mas_bottom).offset(20);
        make.centerX.equalTo(self.view);
        make.size.equalTo(label);
    }];

为新手补充一下,这个类别不只UIView才能用,但凡继承UIView的控件都适用哈,例如UIButtonUIImageViewUILabel等等

上一篇下一篇

猜你喜欢

热点阅读