Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

概要

  • 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 not register and get more from Qiita?
  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