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

Sky*_*ext 6 macos objective-c webview

我刚刚开始开发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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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

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

Ano*_*dya 7

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

#import <WebKit/WebKit.h>
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


CRD*_*CRD 6

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

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

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

建立联系

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

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

@interface AppDelegate : NSObject <NSApplicationDelegate>
{
   WebView *myWebView;
   //other instance variables
}
Run Code Online (Sandbox Code Playgroud)

不会被您的财产使用:

@property (retain, nonatomic) IBOutlet WebView *myWebView;
Run Code Online (Sandbox Code Playgroud)

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

这反过来意味着声明:

[[myWebView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlText]]];
Run Code Online (Sandbox Code Playgroud)

将不会做你期望的,因为myWebView将会,nil而不是指你的WebView.您应该将该物业称为self.myWebView:

[[self.myWebView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlText]]];
Run Code Online (Sandbox Code Playgroud)

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

HTH