[英]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.