// // RichTextLabel.m // BabyAlbum // // Created by mambaxie on 2021/7/3. // #import "RichTextLabel.h" @implementation RichLabelItem + (instancetype)itemWithText:(NSString *)text action:(void (^)(void))action { RichLabelItem *item = [RichLabelItem new]; item.title = text; item.action = action; return item; } @end @implementation RichTextLabel + (instancetype)richTextFullString:(NSString *)fullString items:(NSArray *)items maxWidth:(CGFloat)maxWidth { BOOL isVIP = [fullString containsString:@"iTunes商店"]; RichTextLabel *richLabel = [[RichTextLabel alloc] init]; NSDictionary *attributes = @{NSFontAttributeName:SMALL_FONT, NSForegroundColorAttributeName: [UIColor colorWithWhite:1.0 alpha:0.4]}; if (isVIP) { attributes = @{NSFontAttributeName:SMALL_11_FONT, NSForegroundColorAttributeName: [UIColor colorWithWhite:1.0 alpha:0.4]}; } NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:fullString attributes:attributes]; text.yy_lineSpacing = 2.5; text.yy_alignment = isVIP ? NSTextAlignmentCenter : NSTextAlignmentLeft; for (RichLabelItem *item in items) { //设置高亮色和点击事件 [text yy_setTextHighlightRange:[[text string] rangeOfString:item.title] color:(isVIP ? THEME_COLOR : [UIColor whiteColor]) backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) { if (item.action) { item.action(); } }]; } YYTextContainer *textContainer = [YYTextContainer containerWithSize:CGSizeMake(maxWidth, CGFLOAT_MAX)]; textContainer.maximumNumberOfRows = 0; YYTextLayout *layout = [YYTextLayout layoutWithContainer:textContainer text:text]; richLabel.ignoreCommonProperties = YES; richLabel.textLayout = layout; [richLabel sizeToFit]; return richLabel; } @end @implementation RichLabel + (instancetype)richTextWithFullString:(NSString *)fullString textColor:(UIColor *)textColor font:(UIFont *)font { RichLabel *richLabel = [[RichLabel alloc] init]; NSDictionary *attributes = @{ NSFontAttributeName: font, NSForegroundColorAttributeName: textColor}; NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:fullString attributes:attributes]; richLabel.attributedText = text; return richLabel; } - (void)setRichTextWithText:(NSString *)text textColor:(UIColor *)textColor font:(UIFont *)font { NSMutableAttributedString *attrM = [self.attributedText mutableCopy]; [attrM setAttributes:@{ NSFontAttributeName: font, NSForegroundColorAttributeName: textColor } range:[self.attributedText.string rangeOfString:text]]; self.attributedText = attrM; } @end