Подтвердить что ты не робот

Как показать строку HTML на UILabel в iOS?

Я получаю заголовок в формате HTML как

< span style = "color: # 000000; <strong> Пример </strong> </span> </p>

Мне нужно показать эту строку HTML в UILabel. Цветовой код и размер шрифта должны быть такими же, как и в HTML. Когда я преобразовываю HTML-строку в NSString, приходит только текст "Пример", а не цвет.

Есть ли какое-либо решение?

Thnx заранее

До сих пор я пытаюсь использовать 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;
4b9b3361

Ответ 1

Для 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;

Ответ 2

Swift 2

let htmlText = "<p>etc</p>"

if let htmlData = htmlText.dataUsingEncoding(NSUnicodeStringEncoding) {
    do {
        someLabel.attributedText = try NSAttributedString(data: htmlData,
            options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
            documentAttributes: nil)
    } catch let e as NSError {
        print("Couldn't translate \(htmlText): \(e.localizedDescription) ")
    }
}

Swift 3

let htmlText = "<p>etc</p>"

if let htmlData = htmlText.data(using: String.Encoding.unicode) {
    do {
        let attributedText = try NSAttributedString(data: htmlData, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
    } catch let e as NSError {
        print("Couldn't translate \(htmlText): \(e.localizedDescription) ")
    }
}

Ответ 3

Свифт 4+

Для Swift 4 и выше используйте:

guard let data = "foo".data(using: String.Encoding.unicode) else { return }

try? titleLabel.attributedText = 
   NSAttributedString(data: data,
                   options: [.documentType:NSAttributedString.DocumentType.html], 
        documentAttributes: nil)

Ответ 4

Я сделал это в 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 вместе с его форматированием на ярлыке.

Ответ 5

-(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];

Ответ 6

Расширение для Swift 3

extension UILabel {
    func from(html: String) {
        if let htmlData = html.data(using: String.Encoding.unicode) {
            do {
                self.attributedText = try NSAttributedString(data: htmlData,
                                                             options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
                                                             documentAttributes: nil)
            } catch let e as NSError {
                print("Couldn't parse \(html): \(e.localizedDescription)")
            }
        }
    }
}

Ответ 7

Если текст Html похож на

var planeText = "Unseen and not Purchased!"
//setting color to the text
var htmlText = "<font color=\"#f20707\">" + planeText + "</font>"  

Мы можем установить текст в UILabel следующим образом

if let htmlData = htmlText.data(using: String.Encoding.unicode) {
    do {
         let attributedText = try NSAttributedString(data: htmlData,
             options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], 
             documentAttributes: nil)   
         //Setting htmltext to uilable 
         uilable.attributedText = attributedText

       } catch let e as NSError {
         //setting plane text to uilable cause of err
         uilable.text = planeText
         print("Couldn't translate \(htmlText): \(e.localizedDescription) ")
       }
}