Add TapRecognizer and different color to word inside a string in Xcode
I am pulling a text from a plist and draw it into a 开发者_Python百科UIView. The text contains terms that I want to be highlighted and user interaction enabled so I could pop a dictionary view with the teem explanation.
I know how to find their location on the string and that works fine. But I did not find how to make them a appear in different color. And even more important to me - how to add a tap recognizer to them.
I would appreciate any help.
Thanks Shani
Add a transparent button with the same font and text in front of where the word appears in the UIView. I have a class that will do this with a UILabel if you'd like it? It creates the same effect as with the Facebook application.
O.k i found a solution that works great for me.
i am using UIWebView as The view for the text and then adds the text formatted as HTML. in this way i can use CSS to format the text better and even tag some of the text as link ,in the example i want that the word consonant will appear as a link. (an other great benefit is that I can add support to RTL languishes).
UIWebView *webView =[[UIWebView alloc] initWithFrame:imgViewRect];
webView.backgroundColor = [UIColor clearColor];
webView.opaque=NO;
webView.delegate=self;
NSString *localizedPath = [NSString stringWithFormat:@"rt%@",pcard.card_number];
NSString *localizedString = NSLocalizedString(localizedPath,@"");
NSString *cssPath = [[NSBundle mainBundle] pathForResource:@"style" ofType:@"css"];
//do base url for css
NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
NSString *html =[NSString stringWithFormat:@"<a href=\"consonant\"><dfn>consonant</dfn></a>",
currentLanguage,dir,cssPath,langClass,localizedString];
NSLog(@"%@",html);
[webView loadHTMLString:html baseURL:baseURL];
[self addSubview:webView];
then i use this function to recognize what word clicks and lunch a UIView with the dictionary text:
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request
navigationType:(UIWebViewNavigationType)navigationType {
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
NSURL *URL = [request URL];
NSLog(@"%@",[URL lastPathComponent]); //thats gives me the name of the clicked word.
//here you can set any function that you like.
//using the data from the url path.
}
return YES;
}
hope it will help someone. shani
精彩评论