I have following text in the app integrated within UITextView
By using this application, you agree to our User Agreement and Privacy Policy.
What I want to achieve is to have separate clicks recognized for both bolded sections clicked that are going to open SafariViewController. What I need is something like link recognition where I can put text
By using this application, you agree to our User Agreement(link:@"https://google.com/agreement") and Privacy Policy(link:@"https://google.com/privacy").
I want this text to be shown as the one above, and on click of a textView that it opens these "hidden" links. Is this possible? I've found a solution where a guy creates N number of UILabels (each label is 1 character), attaching gesture recognizers on underlined text. I hate this solution since it is more a hack than a solution when iOS provides you with TextView already that supports linking text.
EDIT:
Found a working solution after few suggestions below and some adjustments...
You need to create UITextView in which you will create your linked text
Create text attributes for normal text, and for text marked as links
NSDictionary *orangeTextAttributes = @{NSForegroundColorAttributeName: [UIColor orangeColor], NSFontAttributeName: [UIFont systemFontOfSize:14 weight:UIFontWeightThin], NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)}; NSDictionary *normalTextAttributes = @{NSForegroundColorAttributeName: [UIColor blackColor], NSFontAttributeName: [UIFont systemFontOfSize:14 weight:UIFontWeightThin]};
Use that attributes to the text
NSMutableAttributedString *labelAttributedText = [[NSMutableAttributedString alloc] initWithString:@"By using this application, you agree to Google's User Agreement and Privacy Policy." attributes:normalTextAttributes]; [self addLink:@"https://google.com/terms-of-services" toString:@"User Agreement" ofAttributedString:labelAttributedText]; [self addLink:@"https://google.com/privacy" toString:@"Privacy Policy" ofAttributedString:labelAttributedText]; self.termsAndPolicyTextView.linkTextAttributes = orangeTextAttributes; self.termsAndPolicyTextView.attributedText = labelAttributedText;
Add method to attach links to your TextView text
- (void)addLink:(NSString *)urlString toString:(NSString *)substringToBeLinked ofAttributedString:(NSMutableAttributedString *)entireAttributedString { NSRange substringRange = [[entireAttributedString string] rangeOfString:substringToBeLinked]; if (substringRange.location != NSNotFound) { [entireAttributedString addAttribute:NSLinkAttributeName value:urlString range:substringRange]; } }
Attack delegate to your text view, and handle callback in which link click is registered
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction { //This is where you open your link in browser for example return NO; }