在NSTextView中创建应用程序内链接

Rog*_*ger 5 cocoa nsurl nstextview

我发现这个小片段允许用户在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];
}
Run Code Online (Sandbox Code Playgroud)

是否可以将链接指向我的应用程序中的某些资源,例如,能够解释链接并分派到相应视图/控制器的特定处理程序类?

Rob*_*ger 6

您可以处理NSTextView委托中链接的点击,特别是通过实施该textView:clickedOnLink:atIndex:方法.

如果需要在每个链接中存储更多信息,可以通过将对象存储为字符串的自定义属性并使用以下链接来执行此操作:

NSDictionary* attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                            yourObject, @"YourCustomAttributeName",
                            @"link", NSLinkAttributeName,
                            nil];
NSAttributedString* string = [[[NSAttributedString alloc] initWithString:@"Your string" attributes:attributes] autorelease];
Run Code Online (Sandbox Code Playgroud)

确保您是否保存使用NSCoding协议的属性字符串而不是RTF方法,NSAttributedString因为RTF无法存储自定义属性.