Search code examples
iosuilabelnsattributedstring

Add a regular action to an NSAttributedString?


I simply want to add an objetive-c action to be called upon a tap on a certain range in my UILabel using NSAttributedString.

But I don't know how to do it. I don't want to open a URL, I just wanna to call a method.

Thanks


Solution

  • You can use NSLinkAttributeName itself to achieve this. Use an attributed string as shown below and set it as the text of a UITextView.

     NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:termsString];
            [attributedString addAttribute:NSLinkAttributeName value:url range:range];
    [myTextView setAttributedText:attributedString];
    

    And then override the UITextView delegate method:

    -(BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange{
    
    // Call your method here.
    return YES;
    }
    

    Dont forget to set the delegate of your textView!