LoginSignup
0
2

More than 1 year has passed since last update.

TextViewのURLをタップしたときのイベント取得

Posted at

TextViewのハイパーリンクをタップしたときにタップしたURLとイベントトリガーが欲しかったので、備忘録。

TextViewに含まれるURLをハイパーリンクとして表示して、タップを検知する。

textView.text = "test \n https://google.com \n Search Google"

textView.isSelectable = true
textView.isEditable = false
textView.delegate = self

// URL部分を遷移可能なリンク化、ハイライト
textView.dataDetectorTypes = .link

textView.linkTextAttributes = [
	.foregroundColor: UIColor.systemBlue,
	.underlineStyle: NSUnderlineStyle.single.rawValue
]

上記の宣言でテキスト中に含まれるURLがハイパーリンクになり、タップ可能になる。

さらにタップした後のイベントトリガーとURLがパラメータとして欲しかったのでl、
クラスにUITextViewDelegateを継承して、デリゲートメソッドtextView(_:shouldInteractWith:in:interaction:)を追加する。

詳しくはドキュメント(https://developer.apple.com/documentation/uikit/uitextviewdelegate/1649337-textview)

func textView(_ textView: UITextView,
			  shouldInteractWith URL: URL,
			  in characterRange: NSRange,
			  interaction: UITextItemInteraction) -> Bool {
	print(URL)
	// URLをデフォルトブラウザで開く
	UIApplication.shared.open(URL)

	return false
}

UIApplication.shared.open(URL)の部分を書き換えれば、リンクタップ時に他にも色々できそうですね

0
2
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
0
2