Just My Life & My Work

曾經以為TextFieldTextView裡的字只能統一屬性來顯示,從iOS 6開始它們都有了attributedText這個屬性,之後可以在字體間顯示不同的效果。

@property(nonatomic,copy)   NSAttributedString     *attributedText NS_AVAILABLE_IOS(6_0); // default is nil



CSS to NSAttributedString - web

此外,可參考先前介紹的文章:多重文字屬性 (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);


    <style type="text/css">
      body {
        font-size: 25px;
        font-family: Avenir, Arial, sans-serif;
        color: greenyellow;
      <p>This is the first line</p>
      <p>This is the happy second line</p>


CSS to NSAttributedString - app

參考:How to add CSS of an html to NSAttributedString

Comments on: "[iOS] HTML的CSS轉為NSAttributedString" (1)



WordPress.com 標誌

您的留言將使用 WordPress.com 帳號。 登出 /  變更 )

Google photo

您的留言將使用 Google 帳號。 登出 /  變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 /  變更 )


您的留言將使用 Facebook 帳號。 登出 /  變更 )

連結到 %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.


%d 位部落客按了讚: