Edit
See my answer for a full working solution:
I managed to solve this myself by using a UITextView
instead of a UILabel
For Dan Bray's solution above to work for me I had to call super.hitTest(point, with:event)
instead of returning nil
. Otherwise touchesBegan
and touchesEnded
were not invoked. I use the textViews inside a UIScrollView
.
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
var location = point
location.x -= self.textContainerInset.left
location.y -= self.textContainerInset.top
if location.x > 0 && location.y > 0 {
let index = self.layoutManager.characterIndex(for: location, in: self.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
for textLink in textLinks {
let range = ((text ?? "") as NSString).range(of: textLink.0)
if NSLocationInRange(index, range) {
callback = {
self.linkDelegate?.didTap(text: textLink.0, withLink: textLink.1, inTextView: self)
}
return self
}
}
}
callback = nil
return super.hitTest(point, with:event)
}