Skip to content

Instantly share code, notes, and snippets.

@manchan
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manchan/83dca87e8ad66c9c372b to your computer and use it in GitHub Desktop.
Save manchan/83dca87e8ad66c9c372b to your computer and use it in GitHub Desktop.
Swiftでテキスト内リンク&テキストタップ検出 ref: http://qiita.com/you_matz/items/bbf0e6632cc56823948a
textView.userInteractionEnabled = true
textView.editable = false
// tapでテキストのポジション検出可能とするため
textView.selectable = true
// 行間レイアウト用
// textView.layoutManager.delegate = self
let text = "Swiftでテキスト内リンク&テキストタップ検出"
let linkText = "リンク"
let nsTex = text as NSString
let link = text.rangeOfString(linkText)
let attributedString = NSMutableAttributedString(string: text)
// リンク位置範囲生成 startからlength
range = NSMakeRange(distance(text.startIndex, link!.startIndex), distance(link!.startIndex, link!.endIndex))
// テキスト全体文字色
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.whiteColor(), range: NSMakeRange(0, nsTex.length))
// リンクカラー
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blueColor(), range: range)
// リンク下線
attributedString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.StyleSingle.rawValue, range: range)
// 属性を代入
textView.attributedText = attributedString
// gesture追加
let tap = UITapGestureRecognizer(target: self, action: "tapText:")
textView.addGestureRecognizer(tap)
func tapText(tap: UITapGestureRecognizer) {
// タップされた座標をもとに最寄りの文字列の位置を取得
let location = tap.locationInView(textView)
let textPosition = textView.closestPositionToPoint(location)
// テキストの先頭とタップした文字の距離をNSIntegerで取得
let selectedPosition = firstTextView.offsetFromPosition(firstTextView.beginningOfDocument, toPosition: textPosition!)
// タップした文字がリンク文字のrangeに含まれるか判定
if NSLocationInRange(selectedPosition, range) {
// リンクタップ時の処理
// let webVC = WebViewController()
// self.presentViewController(webVC, animated: true, completion: nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment