ios - Making different parts of an NSString clickable -


in app reading in text file on server. when nsstring want make different parts of clickable if click on sentence, open dialog box. how go this?

i have read using uitapgesturerecognizer not sure how use recognize string of text rather single word @ time.

i have looked nsmutableattributedstrings not finding need make sense of how this.

any appreciated.

you can use nsattributedstring insert link custom url scheme. then, when detect link has been pressed, check url scheme , if it's yours, whatever want in method. have use uitextview, or can use tttattributedlabel (you can find tttattributedlabel here). following sample code (inspired older ray wenderlich article) uses uitextview.

nsmutableattributedstring *attributedstring = [[nsmutableattributedstring alloc] initwithstring:@"something should happen when press _here_"]; [attributedstring addattribute:nslinkattributename                          value:@"yoururlscheme://_here_"                          range:[[attributedstring string] rangeofstring:@"_here_"]];  nsdictionary *linkattributes = @{nsforegroundcolorattributename: [uicolor greencolor],                              nsunderlinecolorattributename: [uicolor lightgraycolor],                              nsunderlinestyleattributename: @(nsunderlinepatternsolid)};  // assume textview uitextview created (either code or interface builder) textview.linktextattributes = linkattributes; // customizes appearance of links textview.attributedtext = attributedstring; textview.delegate = self; 

then, catch tap on link, implement following uitextviewdelegate method:

- (bool)textview:(uitextview *)textview shouldinteractwithurl:(nsurl *)url inrange:(nsrange)characterrange {     if ([[url scheme] isequaltostring:@"yoururlscheme"]) {         nsstring *tappedword = [url host];          // word, here can show dialogbox         // ...         return no; // if don't return no after handling url, system try handle itself, won't recognize custom urlscheme     }     return yes; // let system open url } 

i find uitextview nsattributedstring , custom urls quite powerful, can lot of things them, can send parameters through url, can convenient sometimes.

you can change url scheme makes more sense in case (instead of yoururlscheme). sure change both when create url , when handle , check url scheme. can have multiple url schemes, example, if want have multiple behaviours when tapping on text in textview.


Comments

Popular posts from this blog

c++ - No viable overloaded operator for references a map -

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - Cannot secure connection using TLS -