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