曾經以為TextField和TextView裡的字只能統一屬性來顯示,從iOS 6開始它們都有了attributedText這個屬性,之後可以在字體間顯示不同的效果。
@property(nonatomic,copy) NSAttributedString *attributedText NS_AVAILABLE_IOS(6_0); // default is nil
現在我們想更進一步知道,如何將HTML的CSS轉為NSAttributedString,之後看到網頁排版漂亮,就可直接拿來套用!
這是html呈現的字樣~
此外,可參考先前介紹的文章:多重文字屬性 (Multiple Text Attribute)、LABEL裡的行距、LABEL裡的字距。
幾行程式設定就能實現喔!記得options的key和value在iOS 7以後才能運作。
/** Theme: CSS of an html to NSAttributedString IDE: Xcode 6 Language: Objective C Date: 104/04/01 Author: HappyMan Blog: https://cg2010studio.wordpress.com/ */ NSURL *htmlString = [[NSBundle mainBundle] URLForResource:@"happy" withExtension:@"html"]; NSAttributedString *stringWithHTMLAttributes = [[NSAttributedString alloc] initWithFileURL:htmlString options: @{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:nil]; self.textView.attributedText = stringWithHTMLAttributes; // // @"DocumentType", one of the document types declared above. For reader methods, this key in options can specify the document type for interpreting the contents. Upon return, the document attributes can contain this key for indicating the actual format used to read the contents. For write methods, this key specifies the format for generating the data. UIKIT_EXTERN NSString *const NSDocumentTypeDocumentAttribute NS_AVAILABLE_IOS(7_0); // Supported document types for the NSDocumentTypeDocumentAttribute key in the document attributes dictionary. UIKIT_EXTERN NSString *const NSHTMLTextDocumentType NS_AVAILABLE_IOS(7_0);
測試時我們要自行準備檔案放在專案下,並命名為happy.html,內容如下:
<html> <head> <style type="text/css"> body { font-size: 25px; font-family: Avenir, Arial, sans-serif; color: greenyellow; } </style> </head> <body> <p>This is the first line</p> <p>This is the happy second line</p> </body> </html>
編譯執行後畫面~
Comments on: "[iOS] HTML的CSS轉為NSAttributedString" (1)