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

Показать текст HTML в UILabel iphone

Я получаю HTML-ответ от веб-службы Ниже приведен HTML-код, который я получаю в ответ

<p><strong>Topic</strong>Gud mrng.</p>
\n<p><strong>Hello Everybody</strong>: How are you.</p>
\n<p><strong>I am fine</strong>: 1 what about you.</p>

Мне нужно отобразить текст в UILabel.

Пожалуйста, помогите

4b9b3361

Ответ 1

Используйте RTLabel-библиотеку для преобразования текста HTML. Я использовал его несколько раз. Оно работает. Вот ссылка на библиотеку и пример кода.

https://github.com/honcheng/RTLabel.

Надеюсь, я помог.

Ответ 2

Вы можете сделать это без каких-либо сторонних библиотек, используя атрибутный текст. Я считаю, что он принимает HTML-фрагменты, такие как тот, который вы получаете, но вы можете обернуть его в полный HTML-документ, чтобы вы могли указать CSS:

static NSString *html =
    @"<html>"
     "  <head>"
     "    <style type='text/css'>"
     "      body { font: 16pt 'Gill Sans'; color: #1a004b; }"
     "      i { color: #822; }"
     "    </style>"
     "  </head>"
     "  <body>Here is some <i>formatting!</i></body>"
     "</html>";

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);

Не кратким, но вы можете скрыть беспорядок, добавив категорию в 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 <b>bold!</b>"];

Ответ 3

Swift 4: версия

extension String {
    func htmlAttributedString() -> NSAttributedString? {
        guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
        guard let html = try? NSMutableAttributedString(
            data: data,
            options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html],
            documentAttributes: nil) else { return nil }
        return html
    }
}

Swift 3: версия

extension String {
func htmlAttributedString() -> NSAttributedString? {
    guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
    guard let html = try? NSMutableAttributedString(
        data: data,
        options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
        documentAttributes: nil) else { return nil }
    return html
    }
}

Swift 2: версия

extension String {
        func htmlAttributedString() -> NSAttributedString? {
            guard let data = self.dataUsingEncoding(NSUTF16StringEncoding, allowLossyConversion: false) else { return nil }
            guard let html = try? NSMutableAttributedString(
              data: data, 
              options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], 
              documentAttributes: nil) else { return nil }
            return html
        }
}

используйте это как:

label.attributedText = yourStringVar.htmlAttributedString()

Ответ 4

Swift 4

Я бы скорее предложил расширить NSAttributedString с неудачным удобством init. String не несет ответственности за создание NSAttributedString по своей природе.

extension NSAttributedString {
     convenience init?(html: String) {
        guard let data = html.data(using: String.Encoding.unicode, allowLossyConversion: false) else {
            return nil
        }
        guard let attributedString = try? NSAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) else {
            return nil
        }
        self.init(attributedString: attributedString)
    }
}
label.attributedText = NSAttributedString(html: "<span> Some <b>bold</b> and <a href='#/userProfile/uname'> Hyperlink </a> and so on </span>")

Ответ 5

От: fooobar.com/questions/160211/...


Чтобы преобразовать HTML в обычный текст Загрузить Файл

и используйте

stringByConvertingHTMLToPlainText на NSString


ИЛИ

Вы можете использовать DTCoreText (ранее известный как дополнения NSAttributedString для HTML).

Ответ 6

Вот быстрая версия 2:

    let htmlStringData = NSString(string: "<strong>Your HTML String here</strong>").dataUsingEncoding(NSUTF8StringEncoding)
    guard let html = htmlStringData else { return }

    do {
        let htmlAttrString = try NSAttributedString(data: html, options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
        yourLabel.attributedText = htmlAttrString
    } catch {
        print("An error occured")
    }

Ответ 7

Ответ выше в Swift 3:

    var str = "<html> ... some html ... </html>"

    let htmlStringData = NSString(string: str).data(using: String.Encoding.utf8.rawValue)
    let html = htmlStringData

    do {
        let htmlAttrString = try? NSAttributedString(
                data: html!,
                options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
                documentAttributes: nil
        )
        agreementText.attributedText = htmlAttrString
    } catch {
        print("An error occured")
    }

Ответ 8

Вышеупомянутый ответ в Swift 3:

func htmlAttributedString() -> NSAttributedString? {
    guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
    guard let html = try? NSMutableAttributedString(
        data: data,
        options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
        documentAttributes: nil) else { return nil }
    return html
}

Ответ 9

В последнее время я занимался частичными фрагментами HTML и конвертировал их в атрибутные строки с возможностью добавления атрибутов. Вот моя версия расширения

import Foundation
import UIKit

extension String {
  func htmlAttributedString(attributes: [String : Any]? = .none) -> NSAttributedString? {
    guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return .none }
    guard let html = try? NSMutableAttributedString(
      data: data,
      options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
      documentAttributes: .none) else { return .none }


    html.setAttributes(attributes, range: NSRange(0..<html.length))

    return html
  }
}

Я называю это так:

let attributes = [
  NSForegroundColorAttributeName: UIColor.lightGray,
  NSFontAttributeName : UIFont.systemFont(ofSize: 12).traits(traits: .traitItalic)
]

label?.attributedText = partialHTMLString.htmlAttributedString(attributes: attributes)

Ответ 10

**// Swift 4 compatible | with setting of colour and font options:**

// add following extension to String:

        func htmlAttributed(family: String?, size: CGFloat, color: UIColor) -> NSAttributedString? {

                let sizeInPx = (size * 0.75)

                do {
                  let htmlCSSString = "<style>" +
                    "html *" +
                    "{" +
                    "font-size: \(sizeInPx)pt !important;" +
                    "color: \(color.hexString ?? "#000000") !important;" +
                    "font-family: \(family ?? "SFUIText-Regular"), SFUIText !important;" +
                  "}</style> \(self)"

                  guard let data = htmlCSSString.data(using: String.Encoding.utf8) else {
                    return nil
                  }

                  return try NSAttributedString(data: data,
                                                options: [.documentType: NSAttributedString.DocumentType.html,
                                                          .characterEncoding: String.Encoding.utf8.rawValue],
                                                documentAttributes: nil)
                } catch {
                  print("error: ", error)
                  return nil
                }
              }

        // add following extension to UIColor:

        extension UIColor{

          var hexString:String? {
            if let components = self.cgColor.components {
              let r = components[0]
              let g = components[1]
              let b = components[2]
              return  String(format: "%02X%02X%02X", (Int)(r * 255), (Int)(g * 255), (Int)(b * 255))
            }
            return nil
          }
        }

    // Sample Use:

    yourLabel.attributedText = locationTitle.htmlAttributed(family: yourLabel.font.fontName,
                                                                           size: yourLabel.font.pointSize,
                                                                           color: yourLabel.textColor)

Ответ 11

Иногда нам нужно отобразить HTML-контент на экране с помощью UILabel. Как отобразить HTML-контент в UILabel, мы увидим в этой статье. давайте начнем и достигнем этого.

enter image description here

Цель C:

NSString * htmlString = @"<html><body> <b>  HTML in UILabel is here…. </b> </body></html>";
NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[htmlString
dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute:
NSHTMLTextDocumentType } documentAttributes:nil error:nil];
UILabel * yourLabel = [[UILabel alloc] init];
yourLabel.attributedText = attrStr;

Swift:

var htmlString = '<html><body> <b>  HTML in UILabel is here…. </b> </body></html>'
var attrStr: NSAttributedString? = nil
do {
 if let data = htmlString.data(using: .unicode) {
 attrStr = try NSAttributedString(data: data, options: [
 NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.html.rawValue
 ], documentAttributes: nil)
 }
} catch {
}
var yourLabel = UILabel()
yourLabel.attributedText = attrStr

Ref: https://medium.com/@javedmultani16/html-text-in-uilabel-ios-f1e0760bcac5