在粘贴

时间:2016-10-15 18:53:51

标签: macos cocoa nstextview

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

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

    [super insertTab: sender];
}

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

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

1 个答案:

答案 0 :(得分:0)

如其他问题所述,请查看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];
}