简体   繁体   中英

Creating a tappable text section inside a UITextView

I have the following problem, I have a textview that says something like this "By tapping the "I agree" button, I certify that I have read and agree to the Online Terms and Conditions"

what I want to do is to add a tap gesture recognizer to the part that says "Online Terms and Conditions" and call a method when the user taps this text section, if the user clicks in any other section of the text nothing should happen.

How can I do this? (I can't post any code due to the NDA I signed) :( I hope I can still be helped.

Thanks in advance.

You can use attributed string with the tag NSLinkAttributeName set for the range of tappable text. Then in the textView delegate implement

optional func textView(_ textView: UITextView, shouldInteractWith URL:URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool

Note that your text field must be selectable and non-editable for this to work.

Reference: https://developer.apple.com/reference/uikit/uitextviewdelegate/1649337-textview

Prior to iOS 10 you can use:

optional func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool`

Reference: https://developer.apple.com/reference/uikit/uitextviewdelegate/1618606-textview

If you need to support both use the @available api - put @available(iOS, deprecated: 10.0) before pre-iOS 10 version and @available(iOS 10.0, *) before the one for iOS 10. That way you will avoid compile-time errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM