【问题标题】:Can a non-editable NSTextView highlight links using setAutomaticLinkDetectionEnabled?不可编辑的 NSTextView 可以使用 setAutomaticLinkDetectionEnabled 突出显示链接吗?
【发布时间】:2013-01-02 03:23:43
【问题描述】:

我一直在使用 NSTextView 来显示一些不可编辑的文本,并希望突出显示其字符串中的任何链接。我已经看到了一些解析链接并添加属性的代码。这样可以正常工作,但我想知道是否可以以某种方式重用内置链接检测。

我试过设置:

[textView setEnabledTextCheckingTypes:NSTextCheckingTypeLink];
[textView setAutomaticLinkDetectionEnabled:YES];

并使用:

[textView checkTextInDocument:nil];

设置字符串后。

【问题讨论】:

    标签: cocoa url hyperlink nstextview


    【解决方案1】:

    为了完整起见,这里是我手动添加到 NSTextView 的链接:

    - (void)highlightLinksInTextView:(NSTextView *)view {
      NSDataDetector *linkDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
      NSArray *matches = [linkDetector matchesInString:view.string options:0 range:NSMakeRange(0, view.string.length)];
    
      [view.textStorage beginEditing];
    
      for (NSTextCheckingResult *match in matches) {
        if (!match.URL) continue;
    
        NSDictionary *linkAttributes = @{
          NSLinkAttributeName: match.URL,
        };
    
        [view.textStorage addAttributes:linkAttributes range:match.range];
      }
    
      [view.textStorage endEditing];
    }
    

    不幸的是,每次设置 NSTextView 字符串时都必须调用它。

    【讨论】:

      【解决方案2】:

      我最近偶然发现了这个并创建了一个 NSTextView 子类LinkDetectingTextView.swift。希望这对将来的人有所帮助。

      【讨论】:

        猜你喜欢
        • 2010-11-29
        • 2017-08-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-25
        • 1970-01-01
        相关资源
        最近更新 更多