美文网首页iOS 应用层
UILable 使用 nsattributtstring 添加

UILable 使用 nsattributtstring 添加

作者: 介和 | 来源:发表于2018-12-19 18:59 被阅读0次

    @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);

                    }

                }

            }];

        }

    }

    相关文章

      网友评论

        本文标题:UILable 使用 nsattributtstring 添加

        本文链接:https://www.haomeiwen.com/subject/oecskqtx.html