【问题标题】:Reload WebView from Menu Item (OS X)从菜单项重新加载 WebView (OS X)
【发布时间】:2015-02-08 20:23:52
【问题描述】:

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

提前致谢!

【问题讨论】:

  • 检查webview是否不为nil,你可能忘记在Interface builder中为WebView创建outlet,或者配置不正确。
  • @ecnepsnai 啊,你是对的! webview == nil。有关如何获得正确的 webview 的任何建议? self.webview == nil 也是。
  • 你是在使用界面生成器,还是务实地制作 webview?
  • @ecnepsnai 界面生成器:@property (assign) IBOutlet WebView *webview;
  • 尝试使用(weak, nonatomic),但也可以通过右键单击界面构建器中的webview来检查头文件中的该行与webview之间是否存在关系。

标签: objective-c xcode macos webview webkit


【解决方案1】:

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

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

尝试:

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

调用当前视图控制器

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多