Advertisement
Guest User

Untitled

a guest
Jul 24th, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. fileprivate lazy var layoutManager = NSLayoutManager()
  2. fileprivate lazy var textContainer = NSTextContainer()
  3. fileprivate lazy var textStorage = NSTextStorage()
  4.  
  5. @IBOutlet var lblLabel: UILabel!
  6.  
  7. // in viewDidLoad
  8. let longpress = UILongPressGestureRecognizer(
  9. target: self,
  10. action: #selector(handleLongPressed(_:))
  11. )
  12. lblLabel.addGestureRecognizer(longpress)
  13.  
  14.  
  15. // handle long press
  16. func handleLongPressed(_ gesture: UILongPressGestureRecognizer) {
  17. let location = gesture.location(in: gesture.view)
  18. if let stringValue = text {
  19.  
  20. // Text storage setup
  21. textStorage = NSTextStorage(string: stringValue)
  22. textStorage.addLayoutManager(layoutManager)
  23.  
  24. // Text container setup
  25. textContainer = NSTextContainer(size: frame.size)
  26. textContainer.lineFragmentPadding = 0
  27. textContainer.lineBreakMode = lineBreakMode
  28. textContainer.maximumNumberOfLines = numberOfLines
  29. layoutManager.addTextContainer(textContainer)
  30.  
  31. }
  32.  
  33. let startPoint = self.layoutManager.location(forGlyphAt: 0)
  34. let newlocation = CGPoint(x: location.x - startPoint.x, y: location.y - startPoint.y)
  35. var fraction: CGFloat = 0
  36.  
  37. let charIndex = layoutManager.characterIndex(for: newlocation, in: textContainer, fractionOfDistanceBetweenInsertionPoints: &fraction)
  38.  
  39. let tagger = NSLinguisticTagger(tagSchemes: [NSLinguisticTagSchemeTokenType], options: 0)
  40. tagger.string = text
  41. var range : NSRange = NSRange(location: 0, length: textStorage.length)
  42. let tag = tagger.tag(at: charIndex, scheme: NSLinguisticTagSchemeTokenType, tokenRange: &range, sentenceRange: nil)
  43.  
  44. if let string = tagger.string, tag == NSLinguisticTagWord {
  45. let word = (string as NSString).substring(with: range)
  46. // You have the word: "World"
  47. print("word - (word)")
  48. print("location - (location)")
  49. print("charIndex - (charIndex)")
  50. }
  51. else {
  52. // Punctuation, whitespace or other.
  53. }
  54.  
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement