Cocoa 在模式窗口中使用WebView不起作用?
如何将WebKit的WebView与模式对话框结合使用Cocoa 在模式窗口中使用WebView不起作用?,cocoa,macos,webview,Cocoa,Macos,Webview,如何将WebKit的WebView与模式对话框结合使用 [_webView setMainFrameURL:[NSString fromStdString:url]]; [_nsWindow makeKeyAndOrderFront:nil]; return [NSApp runModalForWindow:_nsWindow]; 上述代码仅适用于Mac OS 10.6。使用10.5,这不是导航到指定的URL。没有runModalForWindow,一切都正常。WebView只在主循环上工作,
[_webView setMainFrameURL:[NSString fromStdString:url]];
[_nsWindow makeKeyAndOrderFront:nil];
return [NSApp runModalForWindow:_nsWindow];
上述代码仅适用于Mac OS 10.6。使用10.5,这不是导航到指定的URL。没有runModalForWindow,一切都正常。
WebView
只在主循环上工作,因此在这种情况下不配合。一种解决方案是自己运行模式会话,并手动保持主循环的活动状态(类似于所建议的)。例如:
请注意,您可能希望使用类似于
-runMode:beforeDate:
的方法来降低CPU负载。我一直在寻找解决方案,现在我可以使用以下代码在模式会话上使用WebView。如果不使用-运行模式:beforeDate
我的WebView无法处理键盘或装载事件:
- (void) OpenURL:(const char *)_url
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[NSApplication sharedApplication];
[NSApp setDelegate:self];
NSString *url = [NSString stringWithUTF8String:_url];
NSLog(@"OpenURL: %@", url);
NSRect windowRect = NSMakeRect(10.0f, 10.0f, 800.0f, 600.0f);
NSWindow *window = [[NSWindow alloc] initWithContentRect:windowRect
styleMask:(NSResizableWindowMask|NSClosableWindowMask|NSTitledWindowMask)
backing:NSBackingStoreBuffered defer:NO];
[window setDelegate:self];
WebView *webview = [[WebView alloc] initWithFrame:windowRect
frameName:@"mainFrame"
groupName:nil];
[webview setFrameLoadDelegate:self];
[[webview mainFrame]
loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
[window setContentView:webview];
[window makeKeyAndOrderFront:nil];
// Modal Session
NSModalSession session = [NSApp beginModalSessionForWindow:window];
_result = NSModalResponseContinue;
while (_result == NSModalResponseContinue) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
_result = [NSApp runModalSession:session];
// The event loop is a runloop data source, so any ui event will
// wake up the source and make this method returns, and so
// you can block the run loop and tell him to wait that
// something append. [2]
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
beforeDate:[NSDate distantFuture]];
[self doSomeWork];
[pool drain];
}
[NSApp endModalSession:session];
[pool release];
}
您需要调用[NSApp stopModal]
,[NSApp abortModal]
或[NSApp stopModalWithCode:yourReturnCode]
如下:
- (void)windowWillClose:(NSNotification *)notification
{
NSLog(@"windowWillClose");
[NSApp stopModal];
}
链接:
- [1] :
- [2] :
- (void)windowWillClose:(NSNotification *)notification
{
NSLog(@"windowWillClose");
[NSApp stopModal];
}