Add a click event to some text in ios NSString

cdub picture cdub · Jan 19, 2015 · Viewed 11k times · Source

I have the following code and want to make parts of my text be clickable and call another UIViewController (not a website).

NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"testing it out @clickhere"];
NSInteger length = str.length;
[str addAttribute:NSForegroundColorAttributeName value:[UIColor bestTextColor] range:NSMakeRange(0,length)];

The NSMutableAttributedString gets set to a UILabel like so:

label.attributedText = str;

Whats the best way to do this? I can't seem to find a great answer.

An example of what I want is suppose I have a UILabel like so with the following text:

This is my label.  Click here to go to UIViewController1 and then go to UIViewController1 by this #tag.

I want the text "here" to be passed for the first click event and the word "#tag" to be passed to the same click event.

Answer

scott picture scott · Jan 20, 2015

What if you used the value field to pass in the destination?

[attributedString addAttribute:NSLinkAttributeName
                         value:[@"destinationController1" stringByAppendingString:username]
                         range:range];

Then override the delegate method:

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
{
    if ([URL.scheme isEqualToString:@"destinationController1"]) {
        // Launch View controller
        return NO;
    }
    return YES;
}