开发者

NSTextView add URL link to the selected Text?

I Have an NSTextView.

开发者_JAVA技巧I just want to add an Attribute (an NSLinkAttributeName) to the selected Text in the NSTextView...

Can You Help me ?

Thanks.


You want to get the view's textStorage (which is basically a mutable attributed string), then add the NSLinkAttributeName attribute to the selected range; the value of that attribute is the URL to link to.

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


Been a while since I played with ObjC but this should do the trick. It replaces the selected text with the original content with your attr appended. Checked through it but please excuse any typos.

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];

See class defs:

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

  • -replaceCharactersInRange:withString:
  • -selectedRange
  • -scrollRangeToVisible: if you want to present your change immediately

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

  • substringWithRange:
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜