【问题标题】:nstextview replace tabs with space during pastenstextview 在粘贴期间用空格替换选项卡
【发布时间】:2017-02-25 01:18:44
【问题描述】:

我有一个子类NSTextView,我想修改用户输入(基于偏好)以用空格替换制表符。到目前为止,我已将 insertTab 方法修改为如下所示:

- (void) insertTab: (id) sender
{
    if(shouldInsertSpaces) {
        [self insertText: @"    "];
        return;
    }

    [super insertTab: sender];
}

但我也想在粘贴事件期间替换空格。我想到的一种解决方案是修改 NSTextStorage replaceCharacter:with: 方法,但我发现如果我将数据加载到文本视图中,它会替换文本。具体来说,我只想修改用户手动输入的文本。

found here 的解决方案建议修改粘贴板,但我不想这样做,因为我不想在用户粘贴到其他地方时弄乱粘贴板。有没有人对我如何做这件事有任何其他建议?

【问题讨论】:

    标签: macos cocoa nstextview


    【解决方案1】:

    如另一个问题中所述,请查看readSelectionFromPasteboard:type:。覆盖它并替换粘贴板。例如:

    - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pboard type:(NSString *)type {
        id data = [pboard dataForType:type];
        NSDictionary *dictionary = nil;
        NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithRTF:data documentAttributes:&dictionary];
        for (;;) {
            NSRange range = [[text string] rangeOfString:@"\t"];
            if (range.location == NSNotFound)
                break;
            [text replaceCharactersInRange:range withString:@"    "];
        }
        data = [text RTFFromRange:NSMakeRange(0, text.length) documentAttributes:dictionary];
        NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:@"MyNoTabsPasteBoard"];
        [pasteboard clearContents];
        [pasteboard declareTypes:@[type] owner:self];
        [pasteboard setData:data forType:type];
        return [super readSelectionFromPasteboard:pasteboard type:type];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 2012-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多