您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 7 技巧

UITextView 也能顯示 HTML:用 NSAttributedString 載入標籤內容

編輯:iOS 7 技巧

要在 App 中顯示 HTML,大家第一個想到的是 UIWebView。但其實如果只是顯示一些帶標籤的靜態內容(粗體、圖片、段落),UITextView 搭配 NSAttributedString 就綽綽有餘,而且捲動與字型控制都更貼近原生元件。

實作

- (void)viewDidLoad
{
    [super viewDidLoad];

    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 40, kScreenWidth,
                                                                        kScreenHeight - 50)];
    [self.view addSubview:textView];

    // HTML 內容
    NSString *htmlStr = @"<p><img src=\"https://img0.imgtn.bdimg.com/it/u=1368418777,3304551799&fm=21&gp=0.jpg\">
    hiuehuirhfiefguihuiefuwifhewufcehsifhoifhiofhwohfwiohfwoicehicehiheifjkhuhuihwefhuiwhfibfiwehfurwhfuiwhfuiwefhuirwhfiw
    <img src=\"https://img0.imgtn.bdimg.com/it/u=331456922,2614791273&fm=21&gp=0.jpg\">
    hviurhrihvuerhviohvoiwehvewiohiowhviowvhoiheiohihuihguguygigdusichvregtgtgegtgvrtvtrbtrbtrbtrbtrbtbtvrgeggergrbrt
    <img src=\"https://img3.imgtn.bdimg.com/it/u=3236147722,3184690082&fm=21&gp=0.jpg\">
    hiuehuirhfiefguihuiefuwifhewufcehsicehicehiheifjkhuhuihwefhuiwhfibfiwehfurwhfuiwhfuiwefhuirwhfiw</p>";

    // 為圖片加上寬度,避免超出螢幕
    NSString *newString = [htmlStr stringByReplacingOccurrencesOfString:@"<img"
        withString:[NSString stringWithFormat:@"<img width=\"%f\"", kScreenWidth - 10]];

    NSAttributedString *attributedString = [[NSAttributedString alloc]
        initWithData:[newString dataUsingEncoding:NSUnicodeStringEncoding]
           options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType}
documentAttributes:nil error:nil];
    textView.attributedText = attributedString;
}

必須設定的 ATS 例外

上面的 HTML 帶有 http 圖片網址,在 iOS 9 之後會被 App Transport Security 攔下,必須在 Info.plist 開放:

<key>App Transport Security Settings</key>
<dict>
    <key>Allow Arbitrary Loads</key>
    <true/>
</dict>

這裡用的是全域放行,方便但並不安全。正式上線前建議改成只針對特定網域開例外的 NSExceptionDomains,並盡快把資源遷到 https。

常用尺寸巨集

// 當前螢幕寬度
#define kScreenWidth  [UIScreen mainScreen].bounds.size.width
// 當前螢幕高度
#define kScreenHeight [UIScreen mainScreen].bounds.size.height

兩個實務提醒

第一,initWithData:options:documentAttributes:error: 是同步解析,HTML 越長、圖片越多,主執行緒阻塞越久,建議放到背景佇列處理後再回主執行緒賦值。

第二,這條路徑只支援靜態 HTML,沒有 JavaScript 互動能力。若內容需要執行 script、處理表單或需要完整的網頁排版,仍然應該改用 WKWebView(而非已被取代的 UIWebView)。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved