Display HTML text in UILabel iphone

前端 未结 11 1994
借酒劲吻你
借酒劲吻你 2020-12-02 14:39

I am getting a HTML Response from a webservice Below is the HTML I am getting in response

TopicGud mrng.

\\n
11条回答
  •  情书的邮戳
    2020-12-02 15:09

    You can do it without any third-party libraries by using attributed text. I believe it does accept HTML fragments, like the one you're getting, but you may want to wrap it in a complete HTML document so that you can specify CSS:

    static NSString *html =
        @""
         "  "
         "    "
         "  "
         "  Here is some formatting!"
         "";
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 200)];
    NSError *err = nil;
    label.attributedText =
        [[NSAttributedString alloc]
                  initWithData: [html dataUsingEncoding:NSUTF8StringEncoding]
                       options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
            documentAttributes: nil
                         error: &err];
    if(err)
        NSLog(@"Unable to parse label text: %@", err);
    

    Not concise, but you can mop up the mess by adding a category to UILabel:

    @implementation UILabel (Html)
    
    - (void) setHtml: (NSString*) html
        {
        NSError *err = nil;
        self.attributedText =
            [[NSAttributedString alloc]
                      initWithData: [html dataUsingEncoding:NSUTF8StringEncoding]
                           options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
                documentAttributes: nil
                             error: &err];
        if(err)
            NSLog(@"Unable to parse label text: %@", err);
        }
    
    @end
    

    [someLabel setHtml:@"Be bold!"];
    

提交回复
热议问题