LoginSignup
1
2

More than 1 year has passed since last update.

【Swift】UITextViewでHTMLを表示してアンカータグをタップ可能にする

Posted at

やりたいこと

UITextViewでhtmlを表示してアンカータグをタップ可能にかっただけなのですが、巷の記事を参考にしても実装が出来なかったので成功体験を共有できればと思います。

環境

  • Xcode:12.5.1
  • Swift:5.4.2

実装

NSAttributedString型に変換する際にオプションを指定してあげるだけです。
これでHTMLとして表示することが可能です。

    textView.attributedText = convertToAttributeString(contents: information.infoContents)

    private func convertToAttributeString(text: String) -> NSAttributedString? {
        guard let data = text.data(using: .utf8) else { return nil }
        do {
            return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
        } catch {
            return nil
        }
    }

アンカータグをタップしたときにブラウザで開けるようにする

UITextViewのプロパティを設定する必要があります。
ポイントは以下の点です。

  • BehaviorのSelectableをtrueにする
  • BehaviorのEditableをfalseにする
  • Data DetectorsのLinkをtrueにする
  • InteractionのUser Interaction Enabledをtrueにする

textview_editing.png
textview_property2.png
これで表示されるリンクをタップするとSafariが立ち上がり対象のURLが表示されるはずです。

1
2
0

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
1
2