2012-01-14 59 views
5

一个在应用程序的链接,我发现这个小片段,使人们在一个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]; 
} 

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

回答

4

您可以处理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而不是RTF方法NSAttributedString,因为RTF不能存储自定义属性。