I need to intercept the click on an link using UITextView in iOS 17. I was using the delegate below, but UITextItemInteraction is deprecated.
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
print(URL)
return false
}
How do I intercept the click on link in Swift now?
Thank you!
All of the
UITextViewDelegatemethods related toshouldInteractWith:have been deprecated as of iOS 17. They have been replaced with 4 new delegate methods that take aUITextItemparameter.Among those 4 are
textView(_:primaryActionFor:defaultAction:).When you see a deprecation warning for using one of the old delegate methods, you can see the following:
Or if you are using code completion while trying to add one of the old deprecated methods you will see:
which points out two possible replacement delegate methods (though it references only part of the signature).
Look for the 4
UITextItemrelated delegate methods in the documentation forUITextViewDelegate.The following should be a replacement for the code in your question:
Or if you want to prevent the menu from appearing when the link is tapped, you might want the following:
If your deployment target is iOS 16 or lower then you can keep using the older delegate methods. You should only need to update if your deployment target is iOS 17.0 or later.