Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- fileprivate lazy var layoutManager = NSLayoutManager()
- fileprivate lazy var textContainer = NSTextContainer()
- fileprivate lazy var textStorage = NSTextStorage()
- @IBOutlet var lblLabel: UILabel!
- // in viewDidLoad
- let longpress = UILongPressGestureRecognizer(
- target: self,
- action: #selector(handleLongPressed(_:))
- )
- lblLabel.addGestureRecognizer(longpress)
- // handle long press
- func handleLongPressed(_ gesture: UILongPressGestureRecognizer) {
- let location = gesture.location(in: gesture.view)
- if let stringValue = text {
- // Text storage setup
- textStorage = NSTextStorage(string: stringValue)
- textStorage.addLayoutManager(layoutManager)
- // Text container setup
- textContainer = NSTextContainer(size: frame.size)
- textContainer.lineFragmentPadding = 0
- textContainer.lineBreakMode = lineBreakMode
- textContainer.maximumNumberOfLines = numberOfLines
- layoutManager.addTextContainer(textContainer)
- }
- let startPoint = self.layoutManager.location(forGlyphAt: 0)
- let newlocation = CGPoint(x: location.x - startPoint.x, y: location.y - startPoint.y)
- var fraction: CGFloat = 0
- let charIndex = layoutManager.characterIndex(for: newlocation, in: textContainer, fractionOfDistanceBetweenInsertionPoints: &fraction)
- let tagger = NSLinguisticTagger(tagSchemes: [NSLinguisticTagSchemeTokenType], options: 0)
- tagger.string = text
- var range : NSRange = NSRange(location: 0, length: textStorage.length)
- let tag = tagger.tag(at: charIndex, scheme: NSLinguisticTagSchemeTokenType, tokenRange: &range, sentenceRange: nil)
- if let string = tagger.string, tag == NSLinguisticTagWord {
- let word = (string as NSString).substring(with: range)
- // You have the word: "World"
- print("word - (word)")
- print("location - (location)")
- print("charIndex - (charIndex)")
- }
- else {
- // Punctuation, whitespace or other.
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement