我有一个带有网页 View 的Mac Cocoa应用程序,其中包含一些文本。我想使用NSTextFinder提供的默认查找栏搜索该文本。阅读NSTextFinder类引用似乎很容易,但我无法显示查找栏。我想念什么?

作为旁注:
-是的,我尝试将findBarContainer设置为不同的 View ,也是一样。我返回到滚动 View 以消除调试的复杂性
-调用performTextFinderAction来执行查找操作

**App Delegate:**

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{

    self.textFinderController = [[NSTextFinder alloc] init];

    self.webView = [[STEWebView alloc] initWithFrame:CGRectMake(0, 0,  self.window.frame.size.width, 200)];
    [[self.window contentView] addSubview:self.webView];

    [self.textFinderController setClient:self.webView];
    [self.textFinderController setFindBarContainer:self.webView.enclosingScrollView];


    [[self.webView mainFrame] loadHTMLString:@"sample string" baseURL:NULL];

}

- (IBAction)performTextFinderAction:(id)sender {
    [self.textFinderController performAction:[sender tag]];
}

**STEWebView**

@interface STEWebView : WebView <NSTextFinderClient>

@end


@implementation STEWebView

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

    }

    return self;
}

- (void)drawRect:(NSRect)dirtyRect
{
    // Drawing code here.
}


- (NSUInteger) stringLength {
    return [[self stringByEvaluatingJavaScriptFromString:@"document.documentElement.textContent"] length];
}

- (NSString *)string {
    return [self stringByEvaluatingJavaScriptFromString:@"document.documentElement.textContent"];
}

最佳答案

在我的测试中,WebView.enclosingScrollView为null。

// [self.textFinderController setFindBarContainer:self.webView.enclosingScrollView];
NSLog(@"%@", self.webView.enclosingScrollView);

NSView上使用以下类别,可以找到扩展了NSScrollView的嵌套 subview ,并将其设置为容器,从而使NSTextFinderWebView中漂亮地显示
@interface NSView (ScrollView)

- (NSScrollView *) scrollView;

@end

@implementation NSView (ScrollView)

- (NSScrollView *) scrollView {
    if ([self isKindOfClass:[NSScrollView class]]) {
        return (NSScrollView *)self;
    }

    if ([self.subviews count] == 0) {
        return nil;
    }

    for (NSView *subview in self.subviews) {
        NSView *scrollView = [subview scrollView];
        if (scrollView != nil) {
            return (NSScrollView *)scrollView;
        }
    }
    return nil;
}

@end

并在您的applicationDidFinishLaunching:aNotification中:
[self.textFinderController setFindBarContainer:[self scrollView]];

关于objective-c - 如何使NSTextFinder出现,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10489765/

10-11 01:04