Help us understand the problem. What is going on with this article?

UITextViewにタップ可能なリンクを挿入する

概要

  • UITextViewにタップ可能なリンクを挿入したい
  • 実装方法はNSMutableAttributedStringのNSLinkAttributeを利用する
  • TapGestureRecognizerを利用する実装方法もあるが、結構手間

完成イメージ

screenshot_01.png

サンプルコード

ViewController.swift
import UIKit

class ViewController: UIViewController, UITextViewDelegate {

    @IBOutlet weak var textView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let baseString = "これは設定アプリへのリンクを含む文章です。\n\nこちらのリンクはGoogle検索です"

        let attributedString = NSMutableAttributedString(string: baseString)

        attributedString.addAttribute(.link,
                                      value: UIApplicationOpenSettingsURLString,
                                      range: NSString(string: baseString).range(of: "設定アプリへのリンク"))

        attributedString.addAttribute(.link,
                                      value: "https://www.google.co.jp/",
                                      range: NSString(string: baseString).range(of: "こちら"))

        textView.attributedText = attributedString

        // isSelectableをtrue、isEditableをfalseにする必要がある
        // (isSelectableはデフォルトtrueだが説明のため記述)
        textView.isSelectable = true
        textView.isEditable = false
        textView.delegate = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    // MARK: - Text View Delegate

    func textView(_ textView: UITextView,
                  shouldInteractWith URL: URL,
                  in characterRange: NSRange,
                  interaction: UITextItemInteraction) -> Bool {

        UIApplication.shared.open(URL)

        return false
    }
}

ポイント

  • addAttributeメソッドの引数rangeはNSRange
  • Stringのrange(of:String)メソッドでなく、NSStingのrange(of:String)メソッドを利用
  • Stringの場合、戻り値はRange<String.Index>型、NSStringの場合、戻り値はNSRange型のため
一部抜粋
attributedString.addAttribute(NSLinkAttributeName,
                                      value: "https://www.google.co.jp/",
                                      range: NSString(string: baseString).range(of: "こちら"))

Github

Githubでソースコードを公開しています。
https://github.com/shtnkgm/LinkTextViewSample

参考

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away