-
-
Save laevandus/326da7f758720379ae068abe68858615 to your computer and use it in GitHub Desktop.
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
private func url(at touches: Set<UITouch>) -> URL? { | |
guard let attributedText = attributedText, attributedText.length > 0 else { return nil } | |
guard let touchLocation = touches.sorted(by: { $0.timestamp < $1.timestamp } ).last?.location(in: self) else { return nil } | |
guard let textStorage = preparedTextStorage() else { return nil } | |
let layoutManager = textStorage.layoutManagers[0] | |
let textContainer = layoutManager.textContainers[0] | |
let characterIndex = layoutManager.characterIndex(for: touchLocation, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil) | |
guard characterIndex >= 0, characterIndex != NSNotFound else { return nil } | |
// Glyph index is the closest to the touch, therefore also validate if we actually tapped on the glyph rect | |
let glyphRange = layoutManager.glyphRange(forCharacterRange: NSRange(location: characterIndex, length: 1), actualCharacterRange: nil) | |
let characterRect = layoutManager.boundingRect(forGlyphRange: glyphRange, in: textContainer) | |
guard characterRect.contains(touchLocation) else { return nil } | |
// Link styled by Apple | |
if let url = textStorage.attribute(.link, at: characterIndex, effectiveRange: nil) as? URL { | |
return url | |
} | |
// Custom link style | |
return textStorage.attribute(.hyperlink, at: characterIndex, effectiveRange: nil) as? URL | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment