美文网首页iOS开发(OC)
ios利用YYLabel在可换行的文本前加带背景色的标签

ios利用YYLabel在可换行的文本前加带背景色的标签

作者: 颜小宋 | 来源:发表于2018-11-02 15:24 被阅读121次

    类似效果图

    YYLabel确实是一个很有用的控件

    //外部使用可直接调用此方法,简单方便

    subStr即前面带背景色标签的文本

    title即标签之后的主标题

    titleFont 主标题的字号

    + (NSMutableAttributedString*)setPartialTextFillColorWithSubStr:(NSString*)subStr title:(NSString*)title titleFont:(CGFloat)titleFont{

        NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc]init];

        paragraph.alignment=NSTextAlignmentLeft;

        paragraph.lineSpacing=3;

        paragraph.hyphenationFactor=1.0;

        NSMutableAttributedString*attrStr = [selfsetString:titleattributes:@{NSFontAttributeName:[UIFontsystemFontOfSize:titleFont],NSParagraphStyleAttributeName: paragraph}subStr:subStrfillColor:goldenYellowinsets:UIEdgeInsetsMake(-1, -2, -1, -2)subStrColor:CenColorsubStrFontSize:titleFont-2];

        returnattrStr;

    }

    + (NSMutableAttributedString*)setString:(NSString*)string attributes:(nullableNSDictionary *)attributes subStr:(NSString*)subStr fillColor:(NSInteger)fillColor insets:(UIEdgeInsets)insets subStrColor:(NSInteger)subStrColor subStrFontSize:(CGFloat)subStrFontSize{

    //将标签文本和主标题文本拼接

        NSString*itemName = [NSStringstringWithFormat:@" %@ %@",subStr,string];

        NSMutableAttributedString *titleAttrStr = [[NSMutableAttributedString alloc] initWithString:itemName attributes:attributes];

    //设置标签的背景色

       YYTextBorder *border = [YYTextBorder new];

        border.fillColor= [UIColorcolorWithHex:fillColor];

        border.insets= insets;

       NSIntegerlength = subStr.length+1;

        [titleAttrStryy_setTextBackgroundBorder:borderrange:NSMakeRange(0, length)];

    //设置标签的文本颜色

        [titleAttrStryy_setColor:[UIColorcolorWithHex:subStrColor]range:NSMakeRange(0, length)];

    //设置标签文本的字号

        [titleAttrStryy_setFont:[UIFontsystemFontOfSize:subStrFontSize]range:NSMakeRange(0, length)];

        returntitleAttrStr;

    }

    相关文章

      网友评论

        本文标题:ios利用YYLabel在可换行的文本前加带背景色的标签

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