58

HTML形式のタイトルを取得しています

<p><span style="color: #000000;"><strong>例</strong></span></p>

この HTML 文字列を UILabel に表示する必要があります。カラー コードとフォント サイズは、HTML に含まれているものと同じにする必要があります。HTML 文字列を NSString に変換すると、テキスト「例」のみが表示され、色は表示されません。

解決策はありますか?

事前にt​​hnx

今まで、次の方法で NSAttributedString を使用しようとしていますが、この方法では HTML 全体が印刷されます。

UIFont *font = [UIFont systemFontOfSize:14.0];
UIFont *secondFont = [UIFont systemFontOfSize:10.0];

NSMutableDictionary *firstAttributes;
NSMutableDictionary *secondAttributes;

NSDictionary *firstAttributeFont = @{NSFontAttributeName:font};
NSDictionary *secondAttributeFont = @{NSFontAttributeName:secondFont};

[firstAttributes addEntriesFromDictionary:firstAttributeFont];
[secondAttributes addEntriesFromDictionary:secondAttributeFont];

[firstAttributes addEntriesFromDictionary:@{NSForegroundColorAttributeName:[UIColor clearColor]}];
[secondAttributes addEntriesFromDictionary:@{NSForegroundColorAttributeName:[UIColor clearColor]}];



NSString* completeString = [NSString stringWithFormat:@"%@",strTitle];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]     initWithString:completeString];
[attributedString setAttributes:firstAttributes range:[completeString rangeOfString:strTitle]];
//   [attributedString setAttributes:secondAttributes range:[completeString rangeOfString:self.secondAttributeText]];
Cell.lbl_Title.attributedText = attributedString;
4

7 に答える 7

130

iOS7以降では、これを使用できます:

NSString * htmlString = @"<html><body> Some html string </body></html>";
NSAttributedString * attrStr = 
  [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] 
                                   options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType}
                        documentAttributes:nil error:nil];

UILabel * myLabel = [[UILabel alloc] init];
myLabel.attributedText = attrStr;
于 2014-04-13T19:22:05.483 に答える
6

私は次のように UITextView でこれを行いました:

[detailView loadHTMLString:[NSString stringWithFormat:@"<div style='text-align:justify; font-size:13px;font-family:HelveticaNeue;color:#362932;'>%@",[model.dict valueForKey:@"description"]] baseURL:nil];

または、RTLabel ライブラリを使用することもできます: https://github.com/honcheng/RTLabelを使用して、HTML テキストをそのフォーマットと共にラベルに表示します。

于 2013-11-13T07:25:34.713 に答える
4
-(NSString*)convertHtmlPlainText:(NSString*)HTMLString{
    NSData *HTMLData = [HTMLString dataUsingEncoding:NSUTF8StringEncoding];
    NSAttributedString *attrString = [[NSAttributedString alloc] initWithData:HTMLData options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:NULL error:NULL];
    NSString *plainString = attrString.string;

    return plainString;
}

UILabel * htmlLabel = [UILabel alloc] init];
htmlLabel.text = [self convertHtmlPlainText:htmlResponse];
于 2014-08-19T07:31:05.723 に答える