objective-c - NSTextFinder 以编程方式设置搜索字符串并清除视觉反馈

标签 objective-c macos cocoa

我有一个使用查找栏的 NSTextView ([textView setUsesFindBar:YES];)。

我有 2 个问题。

  1. 如何清除查找操作的视觉反馈?

    当我以编程方式更改 textView 的内容时,我的问题就出现了。内容更改后,对先前内容的搜索操作的视觉反馈仍然存在。显然,这些黄色框不适用于新内容,因此我需要一种在更改 textView 内容时清除它们的方法。

    注意:我没有实现 NSTextFinderClient 协议(protocol),因为我有一个简单的 textView,查找栏无需任何其他努力即可正常工作。

  2. 如何将搜索字符串发送到查找栏?

最佳答案

我找到了我的答案,下面是其他人的方法。

首先,您需要一个 NSTextFinder 实例,以便您可以控制它。我们在代码中进行设置。

textFinder = [[NSTextFinder alloc] init];
[textFinder setClient:textView];
[textFinder setFindBarContainer:[textView enclosingScrollView]];
[textView setUsesFindBar:YES];
[textView setIncrementalSearchingEnabled:YES];

第一个答案:要清除视觉反馈,我可以做以下两件事。我可以取消视觉反馈...

[textFinder cancelFindIndicator];

或者我可以提醒 NSTextFinder 我即将更改我的 textView 内容...

[textFinder noteClientStringWillChange];

第二个答案:有一个全局 NSFindPboard。您可以使用它来设置搜索。

// change the NSFindPboard NSPasteboardTypeString
NSPasteboard* pBoard = [NSPasteboard pasteboardWithName:NSFindPboard];
[pBoard declareTypes:[NSArray arrayWithObjects:NSPasteboardTypeString, NSPasteboardTypeTextFinderOptions, nil] owner:nil];
[pBoard setString:@"new search" forType:NSStringPboardType];
NSDictionary* options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSTextFinderCaseInsensitiveKey, [NSNumber numberWithInteger:NSTextFinderMatchingTypeContains], NSTextFinderMatchingTypeKey, nil];
[pBoard setPropertyList:options forType:NSPasteboardTypeTextFinderOptions];

// put the new search string in the find bar
[textFinder cancelFindIndicator];
[textFinder performAction:NSTextFinderActionSetSearchString];
[textFinder performAction:NSTextFinderActionShowFindInterface]; // make sure the find bar is showing

不过有个问题。在该代码之后,查找栏中的实际文本字段不会更新。我发现如果我切换第一响应者然后我可以让它更新......

[myWindow makeFirstResponder:outlineView];
[myWindow makeFirstResponder:textView];

关于objective-c - NSTextFinder 以编程方式设置搜索字符串并清除视觉反馈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13839265/

相关文章:

macos - select() 有时阻塞时间超过提供的超时时间

ios - 从其他类调用方法(自身问题)

iphone - IBOutlet 属性是否必须是非原子的?

python - 使用 pyobjc 将元数据写入 pdf

ios - 使用 Firebase 框架向自己发送通知

iphone - 将 ASIHttpRequest PDF 存储为 NSData

objective-c - 如何从本地持久存储中检索要加载到 WebView(或 WebFrame)中的 HTML?

iphone - 如何创建具有可编辑组件的 UITableView?

macos - 使用命令行向图像添加透明像素行

Cocoa 绑定(bind)和应用程序首选项 - 崩溃