iOS NSMutableAttributedString修改UILabel的部分字體、顏色等屬性

NSMutableAttributedString可以修改UILabel的部分文字的顏色、字體等,也可以在UILabel里添加image展示。
1.改變顏色 range是需要修改顏色的文字范圍

+ (NSMutableAttributedString *)changeColorWithColor:(UIColor *)color content:(NSString *)content range:(NSRange)range {
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc]initWithString:content];
    [attributedStr addAttribute:NSForegroundColorAttributeName
                          value:color
                          range:range];
    return attributedStr;
}

2.修改字體

+ (NSMutableAttributedString *)changeFontWithFont:(UIFont *)font content:(NSString *)content range:(NSRange)range {
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc]initWithString:content];
    [attributedStr addAttribute:NSFontAttributeName value:font range:range];
    return attributedStr;
}

3.UILabel里展示本地圖片

+ (NSMutableAttributedString *)addLocalImageInsertTextWithImageName:(NSString *)imageName mutableAttributeString:(NSMutableAttributedString *)mutableAttributeString index:(NSInteger)index imageWidth:(CGFloat)imageWidth imageHeight:(CGFloat)imageHeight{
    UIImage *image = [UIImage imageNamed:imageName];
    NSTextAttachment *attch = [[NSTextAttachment alloc] init];
    attch.image = image;
    attch.bounds = CGRectMake(0, -3, imageWidth, imageHeight);
    NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
    [mutableAttributeString insertAttributedString:string atIndex:index];
    return mutableAttributeString;
}

4.設置UILabel行間距

+ (NSMutableAttributedString *)lineSpacingWithAttributedString:(NSMutableAttributedString *)str lineSpacing:(CGFloat)lineSpacing content:(NSString *)content {
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [str addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, content.length)];
    [paragraphStyle setLineSpacing:lineSpacing];//調(diào)整行間距
    return str;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容