LoginSignup
66
65

More than 3 years have passed since last update.

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

Last updated at Posted at 2017-02-15

概要

  • 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

参考

66
65
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
66
65