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

时间:2012-01-14 01:16:33

标签: 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];
}

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

1 个答案:

答案 0 :(得分:6)

您可以处理NSTextView代表中链接的点击次数,特别是通过实施textView:clickedOnLink:atIndex:方法。

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

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

确保您要保存use the NSCoding protocol的属性字符串,而不是NSAttributedString的RTF方法,因为RTF无法存储自定义属性。

相关问题