UITextViewにHTMLを表示してみた
UITextViewにHTMLを表示したかったので、試してみました。
こちらの記事UITextViewにHTMLを表示する(Swift3版)を参考にして、HTMLをNSAttributedStringに変換するextensionを定義しました。
import Foundation
import UIKit
extension NSAttributedString {
static func parseHTML2Text(sourceText text: String) -> NSAttributedString? {
let encodeData = text.data(using: String.Encoding.utf8, allowLossyConversion: true)
let attributedOptions = [
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType as AnyObject,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue as AnyObject
]
var attributedString: NSAttributedString?
if let encodeData = encodeData {
do {
attributedString = try NSAttributedString(
data: encodeData,
options: attributedOptions,
documentAttributes: nil
)
} catch _ {
}
}
return attributedString
}
}
あとは、こちら↓のようにHTMLを変換して、UITextFieldのattributedTextに代入すればオッケーです。
let htmlText = "<p>UITextFieldにHTMLを表示することができます。<font color=#ff0000>フォントの色</font>も変更できますし、<a href=\"https://www.apple.com/jp/\">リンク</a>も埋め込むことができます。</p>"
let attributedString = NSAttributedString.parseHTML2Text(sourceText: htmlText)
htmlTextView.attributedText = attributedString
文字列のなかに "
ダブルコーテーションがあるとエラーになります。リンクなどでダブルコーテーションをつかうときは、 \
バックスラッシュをダブルコーテーションのまえにつけてください。
実行すると、こちらのようにHTMLのタグを解釈して表示されています。

リンクをタップしたいとき

リンクをタップしたいときは、 Behavior
のSelectable
と Data Detectors
の Link
を有効にします。
HTMLのなかにリンクが埋め込まれている場合は、タップするとSafariに遷移してリンクを開いてくれるようになります。