refactored action for gesture recognizer

Signed-off-by: Matt Bruce <matt.bruce@verizon.com>
This commit is contained in:
Matt Bruce 2023-04-17 13:11:50 -05:00
parent 4642a65977
commit afd9111a95

View File

@ -12,36 +12,18 @@ extension UITapGestureRecognizer {
public func didTapAttributedTextInLabel(_ label: UILabel, inRange targetRange: NSRange) -> Bool { public func didTapAttributedTextInLabel(_ label: UILabel, inRange targetRange: NSRange) -> Bool {
guard let abstractContainer = label.abstractTextContainer() else { return false } guard let attributedText = label.attributedText else { return false }
let textContainer = abstractContainer.0
let layoutManager = abstractContainer.1
let tapLocation = location(in: label) let layoutManager = NSLayoutManager()
let indexOfGlyph = layoutManager.glyphIndex(for: tapLocation, in: textContainer) let textContainer = NSTextContainer(size: label.bounds.size)
let intrinsicWidth = label.intrinsicContentSize.width let textStorage = NSTextStorage(attributedString: attributedText)
layoutManager.addTextContainer(textContainer)
textStorage.addLayoutManager(layoutManager)
// Assert that tapped occured within acceptable bounds based on alignment. let location = location(in: label)
switch label.textAlignment { let characterIndex = layoutManager.characterIndex(for: location, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
case .right:
if tapLocation.x < label.bounds.width - intrinsicWidth {
return false
}
case .center:
let halfBounds = label.bounds.width / 2
let halfIntrinsicWidth = intrinsicWidth / 2
if tapLocation.x > halfBounds + halfIntrinsicWidth { guard let _ = attributedText.attribute(NSAttributedString.Key.action, at: characterIndex, effectiveRange: nil) as? String, characterIndex < attributedText.length else { return false }
return false return true
} else if tapLocation.x < halfBounds - halfIntrinsicWidth {
return false
}
default: // Left align
if tapLocation.x > intrinsicWidth {
return false
}
}
// Affirms that the tap occured in the desired rect of provided by the target range.
return layoutManager.boundingRect(forGlyphRange: targetRange, in: textContainer).contains(tapLocation) && NSLocationInRange(indexOfGlyph, targetRange)
} }
} }