Created
June 30, 2022 18:47
-
-
Save kiarashvosough1999/8fca83d47970fee20c5ff07a4b2c62ea to your computer and use it in GitHub Desktop.
Detect Tap Attributed Text In Label
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
extension UITapGestureRecognizer { | |
func didTapAttributedTextInLabel(label: UILabel, inRange targetRange: NSRange) -> Bool { | |
// Create instances of NSLayoutManager, NSTextContainer and NSTextStorage | |
let layoutManager = NSLayoutManager() | |
let textContainer = NSTextContainer(size: CGSize.zero) | |
let textStorage = NSTextStorage(attributedString: label.attributedText!) | |
// Configure layoutManager and textStorage | |
layoutManager.addTextContainer(textContainer) | |
textStorage.addLayoutManager(layoutManager) | |
// Configure textContainer | |
textContainer.lineFragmentPadding = 0.0 | |
textContainer.lineBreakMode = label.lineBreakMode | |
textContainer.maximumNumberOfLines = label.numberOfLines | |
let labelSize = label.bounds.size | |
textContainer.size = labelSize | |
// Find the tapped character location and compare it to the specified range | |
let locationOfTouchInLabel = self.location(in: label) | |
let textBoundingBox = layoutManager.usedRect(for: textContainer) | |
let textContainerOffset = CGPoint(x: (labelSize.width - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x, y: (labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y) | |
let locationOfTouchInTextContainer = CGPoint(x: locationOfTouchInLabel.x - textContainerOffset.x, y: locationOfTouchInLabel.y - textContainerOffset.y) | |
let indexOfCharacter = layoutManager.characterIndex(for: locationOfTouchInTextContainer, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil) | |
return NSLocationInRange(indexOfCharacter, targetRange) | |
} | |
} | |
extension Range where Bound == String.Index { | |
var nsRange:NSRange { | |
return NSRange(location: self.lowerBound.encodedOffset, | |
length: self.upperBound.encodedOffset - | |
self.lowerBound.encodedOffset) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment