これはアプリの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
}
}