给UIView
添加手势使用block
回调写法
- .h
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UIView (Action)
- (void)extAction:(void (^)(void))action;
@end
NS_ASSUME_NONNULL_END
- .m
#import "UIView+Action.h"
#import <objc/message.h>
@interface UIView ()
@property (nonatomic, copy) void (^action)(void);
@end
@implementation UIView (Action)
- (void)setAction:(void (^)(void))action {
objc_setAssociatedObject(self, @selector(action), action, OBJC_ASSOCIATION_COPY);
}
- (void (^)(void))action {
return objc_getAssociatedObject(self, _cmd);
}
- (void)extAction:(void (^)(void))action {
self.userInteractionEnabled = YES;
[self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(extAddTap)]];
self.action = action;
}
- (void)extAddTap {
if (self.action) {
self.action();
}
}
@end
-
vc
调用
- (void)test {
[_vTest extAction:^{
NSLog(@"tap1");
}];
__weak __typeof(self)weakSelf = self;
[_ivTest extAction:^{
__strong __typeof(weakSelf)strongSelf = weakSelf;
}];
}
网友评论