6

我刚刚开始开发 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 连接时,我在插座列表中找不到“网络视图”。谢谢我在上一篇文章之后更新了我的代码,但仍然无法正常工作。再次感谢您的回复。

4

2 回答 2

8

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

#import <WebKit/WebKit.h>

在此处输入图像描述

于 2013-04-10T09:41:09.493 回答
6

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

您在 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]]];

不会做你所期望的,因为myWebViewnil不会参考你的WebView. 您应该将该属性称为self.myWebView

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

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

高温高压

于 2013-04-10T10:22:05.603 回答