refactored action for gesture recognizer
Signed-off-by: Matt Bruce <matt.bruce@verizon.com>
This commit is contained in:
parent
4642a65977
commit
afd9111a95
@ -11,37 +11,19 @@ import UIKit
|
|||||||
extension UITapGestureRecognizer {
|
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 }
|
|
||||||
let textContainer = abstractContainer.0
|
|
||||||
let layoutManager = abstractContainer.1
|
|
||||||
|
|
||||||
let tapLocation = location(in: label)
|
guard let attributedText = label.attributedText else { return false }
|
||||||
let indexOfGlyph = layoutManager.glyphIndex(for: tapLocation, in: textContainer)
|
|
||||||
let intrinsicWidth = label.intrinsicContentSize.width
|
|
||||||
|
|
||||||
// Assert that tapped occured within acceptable bounds based on alignment.
|
let layoutManager = NSLayoutManager()
|
||||||
switch label.textAlignment {
|
let textContainer = NSTextContainer(size: label.bounds.size)
|
||||||
case .right:
|
let textStorage = NSTextStorage(attributedString: attributedText)
|
||||||
if tapLocation.x < label.bounds.width - intrinsicWidth {
|
layoutManager.addTextContainer(textContainer)
|
||||||
return false
|
textStorage.addLayoutManager(layoutManager)
|
||||||
}
|
|
||||||
case .center:
|
let location = location(in: label)
|
||||||
let halfBounds = label.bounds.width / 2
|
let characterIndex = layoutManager.characterIndex(for: location, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
|
||||||
let halfIntrinsicWidth = intrinsicWidth / 2
|
|
||||||
|
guard let _ = attributedText.attribute(NSAttributedString.Key.action, at: characterIndex, effectiveRange: nil) as? String, characterIndex < attributedText.length else { return false }
|
||||||
if tapLocation.x > halfBounds + halfIntrinsicWidth {
|
return true
|
||||||
return false
|
|
||||||
} 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)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user