从菜单项重新加载WebView(OS X)

时间:2015-02-08 20:23:52

标签: objective-c xcode macos webview webkit

我想在点击某个菜单项时重新加载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中的按钮。这有效,但我需要这个菜单项。

提前致谢!

1 个答案:

答案 0 :(得分:0)

而不是创建新的视图控制器:

    ViewController * vc = [[ViewController alloc] init];

尝试:

    ViewController * vc = (ViewController *)[[[NSApplication sharedApplication] mainWindow] contentViewController];

调用当前视图控制器