Thanks for being a part of WWDC25!

How did we do? We’d love to know your thoughts on this year’s conference. Take the survey here

I want to know how to use TextKit2 to achieve the same functionality as the following code?

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.

Answered by DTS Engineer in 830865022

With TextKit2, you can get the character index at a certain position in the following way:

  1. Use textLayoutFragment(for:) to retrieve the text layout fragment.

  2. Use textLineFragment(forVerticalOffset:requiresExactMatch:) to retrieve the closest text line fragment.

  3. 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.

With TextKit2, you can get the character index at a certain position in the following way:

  1. Use textLayoutFragment(for:) to retrieve the text layout fragment.

  2. Use textLineFragment(forVerticalOffset:requiresExactMatch:) to retrieve the closest text line fragment.

  3. 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.

I want to know how to use TextKit2 to achieve the same functionality as the following code?
 
 
Q