首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS 顯示包含 HTML 標籤字串的最佳方案:NSAttributedString 或 WKWebView

     編輯:程式設計綜合問答

場景

Google Directions API 返回包含 HTML 標籤(<b>, <div>, <p>, 實體 &nbsp;)的導航指引字串,需在原生 UI 中顯示為富文本。

方案一:NSAttributedString (iOS 7+,輕量、原生渲染)


NSString *htmlString = @"Head southwest toward GH Rd...";
NSData *data = [htmlString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *options = @{
    NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
    NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)
};

NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:data
                                                                       options:options
                                                                documentAttributes:nil
                                                                             error:nil];

// 設置到 UILabel / UITextView
textView.attributedText = attributedString;
// 或 UILabel (需 numberOfLines = 0)
label.attributedText = attributedString;
label.numberOfLines = 0;

方案二:WKWebView (完整 HTML/CSS/JS 支援,重量級)


WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
NSString *html = [NSString stringWithFormat:@"%@", htmlString];
[webView loadHTMLString:html baseURL:nil];
[self.view addSubview:webView];

方案三:正則移除標籤(僅需純文本時)


NSString *plainText = [htmlString stringByReplacingOccurrencesOfString:@"<[^>]+>"
                                                            withString:@""
                                                               options:NSRegularExpressionSearch
                                                                 range:NSMakeRange(0, htmlString.length)];
// 再處理實體
plainText = [plainText stringByReplacingOccurrencesOfString:@" " withString:@" "];
plainText = [plainText stringByReplacingOccurrencesOfString:@"&" withString:@"&"];
// ...

對比選擇指南

需求推薦方案
輕量富文本(粗體、顏色、段落),性能敏感NSAttributedString + UILabel/TextView
複雜排版(表格、浮動、CSS 動畫)、需交互WKWebView
僅需純文本、無格式要求正則移除標籤 + 實體解碼

注意事項

  • NSAttributedString 解析 HTML 在**主線程**且**較慢**,大量文本建議後台線程預解析緩存:

DispatchQueue.global(qos: .userInitiated).async {
    let attributed = try? NSAttributedString(data: data, options: options, documentAttributes: nil)
    DispatchQueue.main.async { self.textView.attributedText = attributed }
}
  • iOS 15+ AttributedString (Swift) 支援 Markdown 解析,若後端可改輸出 Markdown 更高效。
  • 總結

    原生 App 顯示 HTML 導航文本,**NSAttributedString 是首選**(輕量、原生、支援基本富文本)。複雜排版用 WKWebView。純文本需求用正則清洗。避免在主線程大量解析 HTML 導致卡頓。

    1. 上一篇文章:
    2. 下一篇文章:
    Copyright © 程式碼之家 All Rights Reserved