NSTextView添加到所选文本的URL链接?

时间:2011-05-24 15:01:59

标签: cocoa nstextview

我有NSTextView

我只想在NSLinkAttributeName ...

中为所选文字添加属性(NSTextView

你能帮助我吗?

感谢。

2 个答案:

答案 0 :(得分:6)

您想要获取视图的textStorage(基本上是一个可变的属性字符串),然后将NSLinkAttributeName属性添加到所选范围;该属性的值是要链接的URL。

[[textView textStorage] addAttribute: NSLinkAttributeName value: url range:[textView selectedRange]];

答案 1 :(得分:-1)

我玩ObjC已经有一段时间,但这应该可以解决问题。它会将所选文本替换为原始内容,并附加您的attr。检查通过它,但请原谅任何错别字。

NSTextView *textView = ...;
NSDictionary *attributes = ...;

//Get selected text string from TextView (see Text superclass) and append attr link
NSRange selRange = [textView selectedRange];
NSMutableString *changedStr = [[[textView string] substringWithRange:selRange] mutableCopy];
[changedStr appendString:[attributes objectForKey:NSLinkAttributeName]];

//Replace the selected text range in the TextView
[textView replaceCharactersInRange:selRange withString:[NSString stringWithString:changedStr]];

[changedStr release];

参见课程定义:

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSText_Class/Reference/Reference.html

  • -replaceCharactersInRange:withString:
  • -selectedRange
  • -scrollRangeToVisible:如果您想立即提出更改

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html

  • substringWithRange: