@interface LinkUILabel : UILabel
@property(nonatomic, copy) void(^onTap)(NSString *link);
@end
@implementation LinkUILabel
- (instancetype)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
[self setup];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
[self setup];
}
return self;
}
- (void)setup {
self.userInteractionEnabled = YES;
[self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapOnLabel:)]];
}
#pragma mark - Action
// handle the gesture recognizer callback and call the category method
- (void)handleTapOnLabel:(UITapGestureRecognizer *)tapGesture {
if (self.onTap != nil) {
[self.attributedText enumerateAttribute:@"WAGLink" inRange:NSMakeRange(0, self.attributedText.length) options:0 usingBlock:^(id _Nullable value, NSRange range, BOOL * _Nonnull stop) {
if (value != nil) {
BOOL didTapLink = [tapGesture didTapAttributedTextInLabel:self inRange:range];
if (didTapLink) {
*stop = YES;
}
if (value && didTapLink && [value isKindOfClass:[NSString class]]) {
self.onTap(value);
}
}
}];
}
}
网友评论