萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> iOS 開發

iOS 富文本實現:單個 Label 設置多種字體顏色

核心類:NSMutableAttributedString

iOS 6+ 引入屬性字串,支援同一字串不同範圍應用不同屬性 (字體、顏色、下劃線、段落樣式等)。

基礎用法:指定範圍設置顏色與字體


UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, 280, 50)];
label.numberOfLines = 0;
label.text = @"歡迎使用 MyApp,點擊這裡登入";

// 1. 建立可變屬性字串
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:label.text];

// 2. 設置「MyApp」為藍色粗體 (假設在第 7-10 字元)
NSRange appRange = NSMakeRange(6, 4); // 索引從 0 開始
[attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:appRange];
[attrStr addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:16] range:appRange];

// 3. 設置「這裡」為紅色、底線 (假設第 13-14 字元)
NSRange linkRange = NSMakeRange(12, 2);
[attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:linkRange];
[attrStr addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:linkRange];

// 4. 應用到 Label
label.attributedText = attrStr;

封裝工具方法:一鍵設置範圍屬性


// UILabel+RichText.h
@interface UILabel (RichText)
- (void)setText:(NSString *)text 
        font:(UIFont *)font 
     textColor:(UIColor *)color 
  highlightRanges:(NSArray *)ranges 
 highlightColor:(UIColor *)highlightColor 
 highlightFont:(UIFont *)highlightFont;
@end

// UILabel+RichText.m
@implementation UILabel (RichText)
- (void)setText:(NSString *)text 
        font:(UIFont *)font 
     textColor:(UIColor *)color 
  highlightRanges:(NSArray *)ranges 
 highlightColor:(UIColor *)highlightColor 
 highlightFont:(UIFont *)highlightFont {
    
    self.font = font;
    self.textColor = color;
    
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:text];
    
    // 基礎屬性
    [attrStr addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, text.length)];
    [attrStr addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0, text.length)];
    
    // 高亮範圍屬性
    for (NSValue *rangeValue in ranges) {
        NSRange range = [rangeValue rangeValue];
        if (range.location + range.length <= text.length) {
            if (highlightFont) {
                [attrStr addAttribute:NSFontAttributeName value:highlightFont range:range];
            }
            if (highlightColor) {
                [attrStr addAttribute:NSForegroundColorAttributeName value:highlightColor range:range];
            }
        }
    }
    
    self.attributedText = attrStr;
}
@end

// 使用範例
[label setText:@"餘額:¥1,234.56 元" 
        font:[UIFont systemFontOfSize:14] 
     textColor:[UIColor darkGrayColor] 
  highlightRanges:@[[NSValue valueWithRange:NSMakeRange(3, 9)]] // ¥1,234.56
 highlightColor:[UIColor redColor] 
 highlightFont:[UIFont boldSystemFontOfSize:16]];

常用屬性鍵值速查 (iOS 7+ / 11+ 現代化鍵名)

屬性iOS 7-10 鍵名iOS 11+ 鍵名值類型說明
字體NSFontAttributeNameNSAttributedString.Key.fontUIFont
前景色NSForegroundColorAttributeName.foregroundColorUIColor
背景色NSBackgroundColorAttributeName.backgroundColorUIColor高亮背景
下劃線NSUnderlineStyleAttributeName.underlineStyleNSNumber (NSUnderlineStyle)單線/雙線/樣式
刪除線NSStrikethroughStyleAttributeName.strikethroughStyleNSNumber
陰影NSShadowAttributeName.shadowNSShadow
段落樣式NSParagraphStyleAttributeName.paragraphStyleNSMutableParagraphStyle行距、對齊、縮進
連結NSLinkAttributeName.linkNSURL配合 UITextView 可點擊
附件NSAttachmentAttributeName.attachmentNSTextAttachment圖片混排
基線偏移NSBaselineOffsetAttributeName.baselineOffsetNSNumber (float)上標/下標
字距NSKernAttributeName.kernNSNumber (float)字符間距

進階:可點擊的連結文字 (UITextView)


UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 200, 280, 100)];
textView.editable = NO;
textView.selectable = YES; // 關鍵:可選中才能點擊連結
textView.dataDetectorTypes = UIDataDetectorTypeLink; // 自動檢測 URL/電話

NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:@"查看服務條款與隱私政策"];
[attr addAttribute:NSLinkAttributeName value:[NSURL URLWithString:@"https://example.com/terms"] range:NSMakeRange(2, 5)]; // "服務條款"
[attr addAttribute:NSLinkAttributeName value:[NSURL URLWithString:@"https://example.com/privacy"] range:NSMakeRange(9, 5)]; // "隱私政策"
[attr addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(2, 5)];
[attr addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(9, 5)];
textView.attributedText = attr;

// Delegate 處理點擊 (可選,阻止 Safari 彈出)
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction {
    // 自定義處理:推入 WebView、原生頁面等
    return NO; // 阻止默認 Safari 打開
}

HTML 轉 AttributedString (支援 CSS 樣式)


NSString *html = @"重要:請閱讀條款";
NSData *data = [html dataUsingEncoding:NSUTF8StringEncoding];
NSAttributedString *attr = [[NSAttributedString alloc] initWithData:data 
                                                          options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} 
                                                   documentAttributes:nil 
                                                                error:nil];
label.attributedText = attr;
// 注意:HTML 解析較慢,大量使用請背景線程預解析快取
copyright © 萬盛學電腦網 all rights reserved