如何使用模式对话框使用WebKit的WebView?
[_webView setMainFrameURL:[NSString fromStdString:url]];
[_nsWindow makeKeyAndOrderFront:nil];
return [NSApp runModalForWindow:_nsWindow];
前面的代码仅适用于Mac OS 10.6。使用10.5,这不会导航到指定的URL。没有runModalForWindow,一切正常。
答案 0 :(得分:8)
WebView
仅适用于主循环,因此在这种情况下不合作。一种解决方案是自己运行模态会话并手动保持主循环(类似于建议的here)。 E.g:
NSModalSession session = [NSApp beginModalSessionForWindow:yourWindow];
int result = NSRunContinuesResponse;
// Loop until some result other than continues:
while (result == NSRunContinuesResponse)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// Run the window modally until there are no events to process:
result = [NSApp runModalSession:session];
// Give the main loop some time:
[[NSRunLoop currentRunLoop] limitDateForMode:NSDefaultRunLoopMode];
// Drain pool to avoid memory getting clogged:
[pool drain];
}
[NSApp endModalSession:session];
请注意,您可能希望使用类似-runMode:beforeDate:
的内容来降低CPU负载。
答案 1 :(得分:1)
我一直在寻找解决方案,现在我可以使用以下代码在模态会话中使用WebView。不使用-runMode: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];
}
链接: