Skip to content

Instantly share code, notes, and snippets.

@laevandus
Created December 15, 2020 18:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laevandus/326da7f758720379ae068abe68858615 to your computer and use it in GitHub Desktop.
Save laevandus/326da7f758720379ae068abe68858615 to your computer and use it in GitHub Desktop.
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