[英]nstextview replace tabs with space during paste
I have a subclasses NSTextView
and I would like to modify user input (based on a preference) to replace tabs with spaces. 我有一个
NSTextView
子类,我想修改用户输入(基于首选项)以将制表符替换为空格。 So far I've modified the insertTab
method to be something like this: 到目前为止,我已经将
insertTab
方法修改为如下所示:
- (void) insertTab: (id) sender
{
if(shouldInsertSpaces) {
[self insertText: @" "];
return;
}
[super insertTab: sender];
}
But I also want to replace spaces during a paste event. 但是我也想在粘贴事件期间替换空格。 One solution I thought of was to modify the NSTextStorage
replaceCharacter:with:
method, but I found this replaces text if I load data into the textview. 我想到的一种解决方案是修改NSTextStorage
replaceCharacter:with:
方法,但是我发现如果将数据加载到textview中,它将替换文本。 Specifically I only want to modify text the user is entering manually. 具体来说,我只想修改用户手动输入的文本。
A solution found here suggests modifying the pasteboard, but I do not want to do that as I don't want to mess up the users pasteboard should they want to paste somewhere else. 此处找到的解决方案建议修改粘贴板,但是我不想这样做,因为我不想弄乱用户粘贴板,如果他们想粘贴到其他地方。 Does anyone have any other suggestions as to how I can go about doing this?
有人对我该如何做有其他建议吗?
As mentioned in the other question, look at readSelectionFromPasteboard:type:
. 如另一个问题所述,请查看
readSelectionFromPasteboard:type:
Override it and replace the pasteboard. 覆盖它并替换粘贴板。 For example:
例如:
- (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];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.