3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[iOS] UITextViewにハイパーリンクを設定する〜テキストの一部を正規表現で抽出して〜

Posted at

これはアプリのUITextViewの一部にハイパーリンクを設定する実装例となります。
取得する文章データから正規表現でリンクを抽出してハイパーリンクを設定します。

ex.swift
func setup(text: String) {
    // リンク設定
    textView.linkTextAttributes = [
        NSAttributedString.Key.foregroundColor: UIColor.maiFontBlue,
        NSAttributedString.Key.underlineStyle: 1
   ]

    // リンクの抽出
    var hyperlinks: [(link: String, word: String)] = []
    do {
        let regex = try NSRegularExpression(pattern: "<a href=\"(.*?)\".*?>(.*?)</a>")
        let nsString = text as NSString
        let matches = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length))
        let links = matches.map { nsString.substring(with: $0.range(at: 1))} // 正規表現のグループ1(1つ目の"(.*?)"部分)を抽出できる
        let words = matches.map { nsString.substring(with: $0.range(at: 2))} // 正規表現のグループ2(2つ目の"(.*?)"部分)を抽出できる
        links.enumerated().forEach { index, link in
            if words.count > index {
                let hyperlink = (link: link, word: words[index])
                hyperlinks.append(hyperlink)
            }
        }
    } catch {
        // Nothing
    }
    
    var attributes: [NSAttributedString.Key: NSObject] = [:]
    attributes[NSAttributedString.Key.foregroundColor] = .black
    textView.attributeText = NSAttributedString(string: text, attributes: attributes)

    // ハイパーリンクの設定
    if hyperlinks.count > 0 {
        let atttributedText = NSMutableAttributedString(attributedString: textView.attributedText)
        let nsText = atttributedText.mutableString
        hyperlinks.forEach { hyperlink in
            let nsrange = nsText.range(of: hyperlink.word)
            atttributedText.addAttribute(.link, value: hyperlink.link, range: nsrange)
        }
        textView.attributedText = atttributedText
    }

}
3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?