Skip to content

Instantly share code, notes, and snippets.

@fumiyasac
Last active December 5, 2015 00:29
Show Gist options
  • Save fumiyasac/f8fa704c966ad95ec5e6 to your computer and use it in GitHub Desktop.
Save fumiyasac/f8fa704c966ad95ec5e6 to your computer and use it in GitHub Desktop.
Swift2.xでUITextView内のテキストをHTMLとして表示する ref: http://qiita.com/fumiyasac@github/items/40c5250fbed9fe705296
//事前の準備としてtargetTextViewというUITextViewのインスタンスを作成。
//配置したUITextViewのインスタンスに対してリンクを有効にする
self.targetTextView.dataDetectorTypes = .Link
//HTMLタグが混在している文字列に対してHTMLで表示させるようにする処理
//※ "(ダブルクオーテーション)の前に、\(バックスラッシュ)をつけること
do {
//対象のテキスト
let htmlText: String =
"テキストカラーは<font color=\"blue\">青色</font>です。<br>" +
"テキストカラーは<font color=\"red\">赤色</font>です。<br>" +
"ヤフージャパンへのリンクは<a href=\"http://www.yahoo.co.jp/\"><strong>こちら</strong></a><br>" +
"CSSスタイルは<strong style=\"color:#663399;\">こんな風に</strong>適用されます。"
//テキストをUTF-8エンコード
let encodedData = htmlText.dataUsingEncoding(NSUTF8StringEncoding)!
//表示データのオプションの設定
let attributedOptions : [String : AnyObject] = [
NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType, //表示データのドキュメントタイプ
NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding, //表示データの文字エンコード
]
//文字列の変換処理の実装(try 〜 catch構文を使っています。)
let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
//HTMLとしてUITextViewに表示する
self.targetTextView.attributedText = attributedString
//ここは例外処理
} catch {
fatalError("Unhandled error: \(error)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment