Advertisement
Guest User

Untitled

a guest
Aug 19th, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. extension UITapGestureRecognizer {
  2.  
  3. func didTapAttributedTextInLabel(label: UILabel, inRange targetRange: NSRange) -> Bool {
  4. // Create instances of NSLayoutManager, NSTextContainer and NSTextStorage
  5. let layoutManager = NSLayoutManager()
  6. let textContainer = NSTextContainer(size: CGSize.zero)
  7. let textStorage = NSTextStorage(attributedString: label.attributedText!)
  8.  
  9. // Configure layoutManager and textStorage
  10. layoutManager.addTextContainer(textContainer)
  11. textStorage.addLayoutManager(layoutManager)
  12.  
  13. // Configure textContainer
  14. textContainer.lineFragmentPadding = 0.0
  15. textContainer.lineBreakMode = label.lineBreakMode
  16. textContainer.maximumNumberOfLines = label.numberOfLines
  17. let labelSize = label.bounds.size
  18. textContainer.size = labelSize
  19.  
  20. // Find the tapped character location and compare it to the specified range
  21. let locationOfTouchInLabel = self.location(in: label)
  22. let textBoundingBox = layoutManager.usedRect(for: textContainer)
  23. let textContainerOffset = CGPoint(x: (labelSize.width - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x,
  24. y: (labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y);
  25. let locationOfTouchInTextContainer = CGPoint(x: locationOfTouchInLabel.x - textContainerOffset.x,
  26. y: locationOfTouchInLabel.y - textContainerOffset.y);
  27. let indexOfCharacter = layoutManager.characterIndex(for: locationOfTouchInTextContainer, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
  28.  
  29. return NSLocationInRange(indexOfCharacter, targetRange)
  30. }
  31.  
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement