Tag Archives: NSTextView

让NSTextView自动检测URL链接

很多新加入OSX开发的朋友经常问, NSTextView 如何显示 URL 链接呢? 其实这跟 NSTextView 没太大关系, 而是 NSAttributedString 的事情.

下面这个例子是一个 NSTextView 时实链接自动检测并高亮显示的例子, 这个例子也是 OSX 下文本语法高亮实现的基本思路.

urltextview

下面就是关键部分的一段代码:

NSError *error = NULL;
NSDataDetector *dataDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:&error];  
NSString *string = [_textView.textStorage string];
NSArray *matches = [dataDetector matchesInString:string options:0 range:NSMakeRange(0, [string length])];
[_textView.textStorage beginEditing];
[_textView.textStorage removeAttribute:NSForegroundColorAttributeName range:NSMakeRange(0, [string length])];
[_textView.textStorage removeAttribute:NSLinkAttributeName range:NSMakeRange(0, [string length])];
for (NSTextCheckingResult *match in matches) {
    NSRange matchRange = [match range];
    if ([match resultType] == NSTextCheckingTypeLink) {
        NSURL *url = [match URL];
        [_textView.textStorage addAttributes:@{NSLinkAttributeName:url.absoluteString} range:matchRange];
    }
}
[_textView.textStorage endEditing];

要注意的一点是, NSTextView 的 textStorage 属性是一个 NSTextStorage 对象, 它是 NSMutableAttributedString 的子类, 这里实际上是对 AttributedString 做操作. (熟悉类关系才能把握整体框架, 新手不要死盯在一个具体的方法上面)

下载例子:
https://github.com/keefo/URLTextView