【问题标题】:NSTextView add URL link to the selected Text?NSTextView 添加 URL 链接到选定的文本?
【发布时间】:2011-05-24 15:01:59
【问题描述】:

我有一个NSTextView

我只想在NSTextView 中的选定文本中添加一个属性(NSLinkAttributeName)...

你能帮帮我吗?

谢谢。

【问题讨论】:

    标签: cocoa nstextview


    【解决方案1】:

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

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

    【讨论】:

    • [[[textView textStorage] attributesSubstringFromRange:[textView selectedRange]] 属性:NSLinkAttributeName atIndex:0 effectiveRange:NULL];
    • [[textView textStorage] removeAttribute:NSLinkAttributeName range:[textView selectedRange]];
    【解决方案2】:

    自从我玩 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:

    【讨论】:

    • 不;这将在可见文本中附加一个 URL,这不是 OP 要求的。
    • 哦,好的。道歉勒鲁金。误解了这个问题。
    • 嗨,是的,这个答案是错误的,但我已经把它留给后代(或任何其他 NSLinkAttributeName 是新领域的人),而不是删除它。我的 Objective-C 有点过时了(尤其是 2011 年),但正在更新中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-15
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    • 1970-01-01
    相关资源
    最近更新 更多