Skip to content

Instantly share code, notes, and snippets.

@mourad-brahim
Created December 28, 2018 15:50
Show Gist options
  • Save mourad-brahim/cbd8611772cc0d855563ea352cc881bf to your computer and use it in GitHub Desktop.
Save mourad-brahim/cbd8611772cc0d855563ea352cc881bf to your computer and use it in GitHub Desktop.
Handle tap action on a specifc text range
import UIKit
extension UITapGestureRecognizer {
/// Use this function to handle tap action on a label's text
///
/// - parameter label: The label instance on which the tap action needs to be handled
/// - parameter targetRange: The range of text you want to handle the tap on it
///
/// - returns: A boolean indicating if the specified text range was tapped
func didTapTextInLabel(_ 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)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment