How to render text with clickable hyperlinks where

2020-08-04 09:52发布

问题:

I'm tryiing to display some text in my app where there might be some URL in the text. I want the URL to be highlighted as hyperlinks and clickable. Furthermore, when it is clicked, I want to supply a callback where I can perform custom action. Of course the URL should be passed back to my callback so I know what to do with it (say open it in an in-app browser etc).

This might sound complicated but basically all the IM apps in the appstore (over 30 of them) have this functionality where a user can send an IM containing a URL and the receiving end can click on it and open the page in an in-app browser.

How is this done? I just can't figure it out. If you have a solution, please provide sample code. Thank you.


BTW:

The answer is NOT A UIWebView (because it is very slow to render multiple instances of it).

The answer is also NOT A UITextView because although it is capable of parsing URL it cannot be set a custom callback on clicks. So it just ends up opening safari.

The answer is also NOT A TTStyledTextLabel because although it is capable of parsing URL and assigning a custom action to it, it needs to be pre-assigned in a URLMap. And obviously in this case we don't know what the URL is before hand. As far as I know you cannot assign ALL url to a custom action.

alt text http://img169.yfrog.com/img169/3373/picture1ufx.png

回答1:

As far as I know you cannot assign ALL url to a custom action.

I gave you directions in your other SO question, so I'm a bit puzzled as to why you haven't read the source I linked to because it answered this exact question. TTURLMap supports catch-alls via the "-from:toViewController:selector" method. For example:

[map from:@"*" toViewController:[ViewController class]
        selector:@selector(someHandler:)];

I'd understand the confusion if you were dealing with a complete undocumented library, but the Three20 library is very well documented to the point of including sample applications that do exactly what you're after.



回答2:

This might sound complicated but basically all the IM apps in the appstore (over 30 of them) have this functionality where a user can send an IM containing a URL and the receiving end can click on it and open the page in an in-app browser.

Yet what you want are custom callbacks, so this is a different functionality. They may be using UITextViews.

You'll probably have to write the code yourself, e.g. text rendering and link detection, or modify TTStyledTextLabel (which, in either case, looks like a good place to start). I do something similar and I just create UIButtons over any links. For link detection code check out Adium's source.