You can use an NSAttributedString
to insert a link with a custom URL scheme. Then, when you detect that the link has been pressed, check the url scheme and if it's yours, do whatever you want to do in that method. You will have to use an UITextView
, or you can also use a TTTAttributedLabel
(you can find the TTTAttributedLabel
here). The following sample code (inspired from older Ray Wenderlich article) uses a UITextView
.
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"Something should happen when you press _here_"];
[attributedString addAttribute:NSLinkAttributeName
value:@"yoururlscheme://_here_"
range:[[attributedString string] rangeOfString:@"_here_"]];
NSDictionary *linkAttributes = @{NSForegroundColorAttributeName: [UIColor greenColor],
NSUnderlineColorAttributeName: [UIColor lightGrayColor],
NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)};
// assume that textView is a UITextView previously created (either by code or Interface Builder)
textView.linkTextAttributes = linkAttributes; // customizes the appearance of links
textView.attributedText = attributedString;
textView.delegate = self;
Then, to actually catch the tap on the link, implement the following UITextViewDelegate method:
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
if ([[URL scheme] isEqualToString:@"yoururlscheme"]) {
NSString *tappedWord = [URL host];
// do something with this word, here you can show your dialogbox
// ...
return NO; // if you don't return NO after handling the url, the system will try to handle itself, but won't recognize your custom urlscheme
}
return YES; // let the system open this URL
}
I find UITextView
with NSAttributedString
and custom URLs to be quite powerful, you can do a lot of things with them, you can also send parameters through your url, which can be very convenient sometimes.
You can change the url scheme to something that makes more sense in your case (instead of the yoururlscheme
). Just be sure to change it both when you create the URL and when you handle it and check for the url scheme. You can also have multiple url schemes, for example, if you want to have multiple behaviours when tapping on text in your textview.