試圖加載網頁要用到loadRequest:方法。需要完成三步:
<1>給出網址:使用URLWithString:方法創建一個NSURL對象,並初始化一個網址
+(id)URLWithString:(NSString *)URLString;
其中,NSString *用來指定網址,它是一個字符串
<2>傳遞網址:使用requestWithURL:方法,將網址傳遞給NSURLRequest對象
+(id)requestWithURL:(NSURL *)theURL;
其中(NSURL *)theURL用來指定NSURL對象
<3>加載網址:將網址傳遞到NSURLRequest對象中後,就可以使用loadRequest:方法將NSURLRequest對象進行加載
-(void)loadRequest:(NSURLRequest *)request;
其中(NSURLRequest *)request用來指定NSURLRequest *對象。
1.創建項目,打開storyboard文件,在視圖庫中拖動Web View網頁。
2.打開ViewController.h文件,實現聲明一個插座變量。
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
{
IBOutlet UIWebView * web;
}
@end
將插座變量和storyboard視圖進行關聯
3.打開ViewController.h實現加載指定網址的網頁內容。
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
//創建NSURL 對象,給出網址
NSURL * url = [NSURL URLWithString:@"http://www.baidu.com"];
//創建NSURLRequest對象,傳遞網址
NSURLRequest * request = [NSURLRequest requestWithURL:url];
//加載網址對應的網頁內容
[web loadRequest:request];
// UIWebView * web = [[UIWebView alloc] initWithFrame:CGRectMake(20, 50, 270, 200)];
// //創建
// [self.view addSubview:web];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}