Skip to content

Instantly share code, notes, and snippets.

@kateinoigakukun
Created April 18, 2017 13:30
Show Gist options
  • Save kateinoigakukun/59a74c29c6193faf645b4e1376fee217 to your computer and use it in GitHub Desktop.
Save kateinoigakukun/59a74c29c6193faf645b4e1376fee217 to your computer and use it in GitHub Desktop.
こうなりました #swift #CodePiece
import UIKit
class LinkTextView: UITextView {
private var interractDate = Date()
var linkTextViewDelegate: LinkTextViewDelegate?
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
interractDate = Date()
return linkURL(at: point) != nil ? self : nil
}
var isLongTap: Bool {
return interractDate.timeIntervalSinceNow < -0.5
}
func linkURL(at point: CGPoint) -> URL? {
guard let tappedPosition = self.closestPosition(to: point) else { return nil }
let tappedOffset = offset(from: beginningOfDocument, to: tappedPosition)
if tappedOffset >= text.length { return nil }
let attributes = attributedText.attributes(at: tappedOffset, effectiveRange: nil)
guard let linkAttribute = attributes[NSLinkAttributeName] as? String else { return nil }
return URL(string: linkAttribute)
}
open override func addGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer) {
if gestureRecognizer is UILongPressGestureRecognizer {
gestureRecognizer.addTarget(self, action: #selector(self.longPressAction(_:)))
super.addGestureRecognizer(gestureRecognizer)
}else if gestureRecognizer is UITapGestureRecognizer {
super.addGestureRecognizer(gestureRecognizer)
}else{
super.addGestureRecognizer(gestureRecognizer)
}
}
func longPressAction(_ gesture: UILongPressGestureRecognizer) {
let location = gesture.location(in: self)
guard let url = linkURL(at: location) else { return }
if isLongTap {
linkTextViewDelegate?.textView(self, longPress: url)
return
}
switch gesture.state {
case .ended:
_ = linkTextViewDelegate?.textView?(self, shouldInteractWith: url, in: NSRange())
default: break
}
}
}
protocol LinkTextViewDelegate: UITextViewDelegate {
func textView(_ textView: UITextView, longPress URL: URL)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment