用Category方式给UITapGestureRecognizer添加Tag属性

.h

#import <UIKit/UIKit.h>

@interface UITapGestureRecognizer (Tag)
/**
 *  tag
 */
@property (nonatomic) int tag;

@end

.m

#import "UITapGestureRecognizer+Tag.h"
#import <objc/runtime.h>


static const void *TAG = &TAG;

@implementation UITapGestureRecognizer (Tag)
@dynamic tag;

/**
 *  @param tag
 */
- (void)setTag:(int)tag {
    objc_setAssociatedObject(self, TAG, [NSNumber numberWithInt:tag], OBJC_ASSOCIATION_RETAIN);
}

/**
 *  返回tag
 *  @return tag
 */
- (int)tag {
    return [objc_getAssociatedObject(self, TAG) intValue];
}
@end

注意

  • 引入头文件
#import <objc/runtime.h>
  • 只能存储object
objc_setAssociatedObject(self, TAG, [NSNumber numberWithInt:tag], OBJC_ASSOCIATION_RETAIN);
  • get方法必须转为int类型
return [objc_getAssociatedObject(self, TAG) intValue];

猜你喜欢

转载自blog.csdn.net/whde_006/article/details/51445943
今日推荐