LoginSignup
2

More than 5 years have passed since last update.

NSAttributedStringを使ってHTMLを表示

Posted at

データに含まれるHTMLをWebViewを使わずに表示したいことってありますよね。
そんなときはNSAttributedStringを使うことで実現が可能です。

NSAttributedStringとは

文字列の属性を管理するためのクラスで、文字列のフォントサイズを変更したり、
装飾を加えたりすることができます。

HTMLを含む文字列を表示

init(data:options:documentAttributes:)で初期化する際に、
のoptionsにNSHTMLTextDocumentTypeを指定してあげます。

let html = "<b>foo</b>bar"
if let data = html.data(using: .utf8) {
    let attr = try? NSAttributedString(data: data,
                                       options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
                                       documentAttributes: nil)
    label.attributedText = attr
}

こんな感じの表示になります。
Simulator Screen Shot 2017.09.10 11.18.41.png

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2