2012-01-14 60 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不能存儲自定義屬性。