iOS 应用层

UILable 使用 nsattributtstring 添加

2018-12-19  本文已影响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);

                }

            }

        }];

    }

}

上一篇 下一篇

猜你喜欢

热点阅读