【问题标题】:Creating an in-app link in NSTextView在 NSTextView 中创建应用内链接
【发布时间】:2012-02-10 04:10:16
【问题描述】:

我发现了这个小 sn-p,它允许从 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];
}

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

【问题讨论】:

    标签: cocoa nsurl nstextview


    【解决方案1】:

    您可以处理对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 无法存储自定义属性。

    【讨论】:

    • 请注意,NSTextView 必须打开其可选择标志,否则您的链接将根本无法点击。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-09
    • 2012-04-16
    • 1970-01-01
    • 2014-03-02
    • 1970-01-01
    • 2015-10-13
    • 1970-01-01
    相关资源
    最近更新 更多