2016-10-15 65 views
0

我有一個小類NSTextView,我想修改用戶輸入(根據首選項)以用空格替換標籤。到目前爲止,我已經修改了insertTab方法是這樣的:nstextview在粘貼期間用空格替換標籤

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

    [super insertTab: sender]; 
} 

但我也希望有一個粘貼事件過程中替換的空間。我想到的一個解決方案是修改NSTextStorage replaceCharacter:with:方法,但是如果我將數據加載到textview中,我發現這會替換文本。具體而言,我只想修改用戶手動輸入的文本。

解決方案found here建議修改粘貼板,但我不想這樣做,因爲我不想弄亂用戶粘貼板,如果他們想粘貼到其他地方。有沒有人有任何其他建議,我可以怎麼做呢?

回答

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