繁体   English   中英

如何在WebView(OSX项目)中启动时加载URL?

[英]How to load URL on launch in a WebView (OSX project)?

我刚刚开始开发mac应用程序,我想在应用程序启动时将WebView作为URL。这是我的代码:

AppDelegate.h

#import <Cocoa/Cocoa.h>
#import <WebKit/WebKit.h>

@interface AppDelegate : NSObject <NSApplicationDelegate> {
     WebView *myWebView;
    //other instance variables
}

@property

(retain, nonatomic) IBOutlet WebView *myWebView;

//other properties and methods

@end

AppDelegate.m

 #import "AppDelegate.h"
#import <WebKit/WebKit.h>

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    NSString *urlText = @"http://google.com";
    [[self.myWebView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlText]]];
    return;
    // Insert code here to initialize your application
}

@end

如何在WebView(OSX项目)中启动时加载URL?

我认为代码工作,但当我尝试在Interface Builder中将代码与WebView连接时,我无法在插座列表中找到“Web视图”。 谢谢我在最后一篇文章后更新了我的代码,但仍然无效。 再次感谢您的回复。

您需要添加WebKit框架。 在此输入图像描述

#import <WebKit/WebKit.h>

在此输入图像描述

很难确定这里的问题是什么,所以猜猜......

你在IB中拖动连接的方式是什么?

要连接插座,您需要从Inspector中显示的插座拖动到Web视图:

建立联系

如果以另一种方式拖动,则从Web视图到大纲中的App Delegate,您尝试连接操作。

您的代码和实例变量中也存在问题:

@interface AppDelegate : NSObject <NSApplicationDelegate>
{
   WebView *myWebView;
   //other instance variables
}

不会被您的财产使用:

@property (retain, nonatomic) IBOutlet WebView *myWebView;

因为你的属性是自动合成的,所以会创建一个实例变量_myWebView 您应该看到编译器警告此效果。

这反过来意味着声明:

[[myWebView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlText]]];

不会做你期望的,因为myWebView将是nil而不是引用你的WebView 您应该将该属性称为self.myWebView

[[self.myWebView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlText]]];

通过这些更改,您应该在网络视图中看到Google。

HTH

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM