LoginSignup
53
57

More than 5 years have passed since last update.

SwiftでUILabelにHTMLを表示する方法

Last updated at Posted at 2014-08-24

SwiftでUILabelにHTMLを表示する方法

Objective-Cとあまり変わらないけど、若干つまづいたのでメモ。
注)UILabelなので、あくまで表示しかできません。<a>タグでリンククリックとかさせたい場合はUIWebView使いましょう

サンプルプロジェクト

サンプルコード

var htmlText = "空は<font color=\"blue\">青い</font>。<br>" +
               "An apple is <font color=\"red\">red</font>."

var err:NSError?
self.htmlLabel.attributedText = NSAttributedString(
                  data: htmlText.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true),
               options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType],
    documentAttributes: nil,
                 error: &err)
self.htmlLabel.font = UIFont(name: "System", size: 14)

実行結果

ScreenShot.png

ポイント

NSAttributedString

基本的には以下のリンク(Obj-C)のとおり、NSAttributedStringを使ってHTMLを変換しています
http://stackoverflow.com/questions/15872257/display-html-text-in-uilabel-iphone

NSErrorはOptionalに

NSErrorの値は必ずnilが入りうるので、?をつけてoptional型にしましょう。
これを忘れると "Extra argument 'data' in call" とか全然関係なさそうなコンパイルエラーになります

fontの設定

HTMLを表示すると、Storyboardで設定したSystemフォントが英字で無効になっちゃうので
あとからUIFontで設定してます。
SwiftではfontWithNameが非推奨になってinitでfont設定するようになったようですね

UILabelのLinesは0に

HTMLに限ったことではないですが、UILabelの値が可変で2行以上表示させたい場合には
StoryBoardでUILabelのLinesを0に設定しておきましょう

Screen Shot 2014-08-24 at 21.52.20.png

53
57
1

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
53
57