不可编辑的NSTextView可以使用setAutomaticLinkDetectionEnabled突出显示链接吗?

问题描述 投票:2回答:2

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

我尝试设置:

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

并使用:

[textView checkTextInDocument:nil];

设置字符串后。

cocoa url hyperlink nstextview
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字符串时,都必须调用此方法。


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.