试图加载网页要用到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.
}