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 に答える