修改 UILabel 文字中某段文字的顏色和大小 - iOS

一段文字中的某一段內(nèi)容需要將其變得更加突顯出來(lái),為了復(fù)雜多余的操作流程,便通過(guò)如下的方法將內(nèi)容進(jìn)行調(diào)整,更加簡(jiǎn)便方便。

GitHub - 聲明
GitHub - 實(shí)現(xiàn)

/**
 改變 label 文字中某段文字的顏色和大小
 label      傳入的文本內(nèi)容(注:傳入前要有文字)
 oneIndex   從首位文字開始
 endIndex   至末位文字結(jié)束
 color      字體顏色
 size       字體字號(hào)
 */
+ (void)YHLabelAttributedString:(UILabel *)label firstText:(NSString *)oneIndex toEndText:(NSString *)endIndex textColor:(UIColor *)color textSize:(CGFloat)size;
+ (void)YHLabelAttributedString:(UILabel *)label firstText:(NSString *)oneIndex toEndText:(NSString *)endIndex textColor:(UIColor *)color textSize:(CGFloat)size {
    // 創(chuàng)建 Attributed
    NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:label.text];
    // 需要改變的首位文字位置
    NSUInteger firstLoc = [[noteStr string] rangeOfString:oneIndex].location;
    // 需要改變的末位文字位置
//    NSUInteger endLoc = [[noteStr string] rangeOfString:endIndex].location + 1;
    NSUInteger endLoc = [[noteStr string] rangeOfString:endIndex].location + [[noteStr string] rangeOfString:endIndex].length;
    // 需要改變的區(qū)間
    NSRange range = NSMakeRange(firstLoc, endLoc - firstLoc);
    // 改變顏色
    [noteStr addAttribute:NSForegroundColorAttributeName value:color range:range];
    // 改變字體大小及類型
    [noteStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"PingFangSC-Regular" size:size] range:range];
    // 為 label 添加 Attributed
    [label setAttributedText:noteStr];
}

以上便是此次分享的全部?jī)?nèi)容,希望能對(duì)大家有所幫助!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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