2

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

我试过设置:

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

并使用:

[textView checkTextInDocument:nil];

设置字符串后。

4

2 回答 2

2

为了完整起见,这里是我手动添加到 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 字符串时都必须调用它。

于 2013-01-30T12:50:43.510 回答
1

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

于 2020-04-18T13:47:00.687 回答