UILable 使用 nsattributtstring 添加 点击事件

@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:@"test_Link" 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);

                }

            }

        }];

    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容