[英]Reload WebView from Menu Item (OS X)
我想在每次單擊某個菜單項時重新加載WebView
。 這是我的代碼不起作用。 (假定.h
文件中的普通聲明。)
// AppDelegate.m
#import "AppDelegate.h"
// #import "ViewController.h" (in AppDelegate.h)
@interface AppDelegate ()
@end
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Insert code here to initialize your application
}
- (void)applicationWillTerminate:(NSNotification *)aNotification {
// Insert code here to tear down your application
}
// Menu Item triggers this:
- (IBAction)reloadWebView:(id)sender {
NSLog(@"AppDelegate reloadWebView");
ViewController * vc = [[ViewController alloc] init];
[vc reloadWebView:sender]; // tried this,
[vc.webview reload:sender]; // and this,
[[vc.webview mainFrame] reload]; // and this,
[[vc.webview mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com/"]]]; // and this.
}
@end
// ViewController.m
#import "ViewController.h"
// @property (assign) IBOutlet WebView *webview; (in ViewController.h)
@implementation ViewController
@synthesize webview;
- (void)viewDidLoad {
[super viewDidLoad];
[[webview mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com/"]]]; // this works
}
- (void)setRepresentedObject:(id)representedObject {
[super setRepresentedObject:representedObject];
// Update the view, if already loaded.
}
// Called in AppDelegate:
- (void)reloadWebView:(id)sender {
NSLog(@"ViewController reloadWebView");
// The problem here seems to be: webview == nil
[webview reload:sender]; // also tried this,
[[webview mainFrame] reload]; // and this,
[[webview mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com/"]]]; // and this.
}
@end
這就是我的全部代碼。 我剛剛開始從事這個項目。
我試過使用ViewController
的按鈕。 那行得通,但我需要將此作為菜單項。
提前致謝!
而不是創建新的視圖控制器:
ViewController * vc = [[ViewController alloc] init];
嘗試:
ViewController * vc = (ViewController *)[[[NSApplication sharedApplication] mainWindow] contentViewController];
調用當前的視圖控制器
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.