描述:UIWebVIew 是IOS一个常见的控件,属内置的浏览器控件,可以用来加载网页,或是打开文件等等。
方法一:
代码实现:(运行程序时,直接显示链接的内容)
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSURL * url=[NSURL URLWithString:@"http://www.baidu.com"];
NSURLRequest * request=[[NSURLRequest alloc]initWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
UIWebView * webView=[[UIWebView alloc]initWithFrame:self.view.frame];
[webView loadRequest:request];
[self.view addSubview:webView];
}];
}
@end
方法二:
效果图:
代码实现:
首先用storyboard搭建大体框架
#import "ViewController.h"
@interface ViewController ()<UIWebViewDelegate>
//左上角 后退按钮
@property (weak, nonatomic) IBOutlet UIBarButtonItem *backItem;
//右上角 前进按钮
@property (weak, nonatomic) IBOutlet UIBarButtonItem *forwardItem;
//静态label
@property (weak, nonatomic) IBOutlet UILabel *label;
//输入框
@property (weak, nonatomic) IBOutlet UITextField *textFiled;
@property (weak, nonatomic) UIWebView * webView;
- (IBAction)back;
- (IBAction)forward;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIButton * button=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 70, 30)];
button.center=self.view.center;
button.backgroundColor=[UIColor redColor];
[button setTitle:@"搜索" forState:UIControlStateNormal];
[button addTarget:self action:@selector(search) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview: button];
}
#pragma mark - 按钮的点击事件
- (IBAction)back
{
[self.webView goBack];
}
- (IBAction)forward
{
[self.webView goForward];
}
- (void) search
{
//创建webView
UIWebView * webView=[[UIWebView alloc]init];
webView.frame=CGRectMake(0, 69, self.view.frame.size.width, self.view.frame.size.height-69);
self.webView=webView;
[self.view addSubview:webView];
//加载请求
NSString * str=self.textFiled.text;
NSURL * url=[NSURL URLWithString:str];
NSURLRequest * request=[NSURLRequest requestWithURL:url];
[webView loadRequest:request];
//设置代理
webView.delegate=self;
}
#pragma mark - UIWebViewDelegate代理方法
- (void) webViewDidFinishLoad:(UIWebView *)webView
{
self.backItem.enabled = [webView canGoBack];
self.forwardItem.enabled = [webView canGoForward];
}
@end