Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an in-app link in NSTextView

I found this little snippet which allows one to create links from text in an NSTextView:

-(void)setHyperlinkWithTextView:(NSTextView*)inTextView
{
    // create the attributed string
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] init];

    // create the url and use it for our attributed string
    NSURL* url = [NSURL URLWithString: @"http://www.apple.com"];
    [string appendAttributedString:[NSAttributedString hyperlinkFromString:@"Apple Computer" withURL:url]];

    // apply it to the NSTextView's text storage
    [[inTextView textStorage] setAttributedString: string];
}

Would it be possible to have the link point to some resource in my application, for example to a specific handler class that is capable of interpreting the links and dispatch to a corresponding view/controller?

like image 659
Roger Avatar asked Jan 14 '12 01:01

Roger


1 Answers

You can handle clicks on the links in your NSTextView delegate, specifically by implementing the textView:clickedOnLink:atIndex: method.

If you need to store more information with each link, you can do this by storing an object as a custom attribute of the string with the link:

NSDictionary* attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                            yourObject, @"YourCustomAttributeName",
                            @"link", NSLinkAttributeName,
                            nil];
NSAttributedString* string = [[[NSAttributedString alloc] initWithString:@"Your string" attributes:attributes] autorelease];

Make sure if you're saving the attributed string that you use the NSCoding protocol and not the RTF methods of NSAttributedString because RTF cannot store custom attributes.

like image 113
Rob Keniger Avatar answered Sep 28 '22 02:09

Rob Keniger