【发布时间】: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