The main function of this code is that when I click on the link within the TextView, the TextView will respond to the event, while when clicking on other places, the TextView will not respond to the event.
I want to know how to use TextKit2 to achieve the same functionality as the following code?
class MyTextView: UITextView {
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
var location = point
location.x -= textContainerInset.left
location.y -= textContainerInset.top
let characterIndex = layoutManager.characterIndex(for: location, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
if characterIndex < textStorage.length, characterIndex >= 0 {
if let _ = textStorage.attribute(.link, at: characterIndex, effectiveRange: nil) {
return self
}
}
return nil
}
}
I haven't found a method similar to that in Textkit1 within Textkit2. I'm looking forward to everyone's guidance.
With TextKit2, you can get the character index at a certain position in the following way:
-
Use textLayoutFragment(for:) to retrieve the text layout fragment.
-
Use textLineFragment(forVerticalOffset:requiresExactMatch:) to retrieve the closest text line fragment.
-
Use characterIndex(for:) to retrive the character index.
The coordinate systems used in the above APIs are different, and so you need to convert the point you get from hitTest
to the right coordinate system.
Best,
——
Ziqiao Chen
Worldwide Developer Relations.