How do you use NSAttributedString?

后端 未结 15 945
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 04:19

Multiple colours in an NSString or NSMutableStrings are not possible. So I\'ve heard a little about the NSAttributedString which was introduced wit

15条回答
  •  [愿得一人]
    2020-11-22 04:51

    Since iOS 7 you can use NSAttributedString with HTML syntax:

    NSURL *htmlString = [[NSBundle mainBundle]  URLForResource: @"string"     withExtension:@"html"];
    NSAttributedString *stringWithHTMLAttributes = [[NSAttributedString alloc] initWithFileURL:htmlString
                                                                                           options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType}
                                                                                documentAttributes:nil
                                                                                             error:nil];
    textView.attributedText = stringWithHTMLAttributes;// you can use a label also
    

    You have to add the file "string.html" to you project, and the content of the html can be like this:

    
      
        
      
      
        firstsecondthird
      
      
    

    Now, you can use NSAttributedString as you want, even without HTML file, like for example:

    //At the top of your .m file
    #define RED_OCCURENCE -red_occurence-
    #define GREEN_OCCURENCE -green_occurence-
    #define BLUE_OCCURENCE -blue_occurence-
    #define HTML_TEMPLATE @"-red_occurence--green_occurence--blue_occurence-"
    
    //Where you need to use your attributed string
    NSString *string = [HTML_TEMPLATE stringByReplacingOccurrencesOfString:RED_OCCURENCE withString:@"first"] ;
    string = [string stringByReplacingOccurrencesOfString:GREEN_OCCURENCE   withString:@"second"];
    string = [string stringByReplacingOccurrencesOfString:BLUE_OCCURENCE    withString:@"third"];
    
    NSData* cData = [string dataUsingEncoding:NSUTF8StringEncoding];
    
    NSAttributedString *stringWithHTMLAttributes = [[NSAttributedString alloc] initWithData:cData
                                                                                    options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType}
                                                                            documentAttributes:nil
                                                                                         error:nil];
    textView.attributedText = stringWithHTMLAttributes;
    

    Source

提交回复
热议问题