webView(简单的浏览器)
1 #import "MJViewController.h"
2
3 @interface MJViewController () <UISearchBarDelegate, UIWebViewDelegate>
4
5 @property (weak, nonatomic) IBOutlet UIWebView *webView;
6 @property (weak, nonatomic) IBOutlet UIBarButtonItem *backButton;
7 @property (weak, nonatomic) IBOutlet UIBarButtonItem *forwarButton;
8
9 @end
10
11 @implementation MJViewController
12
13 - (void)viewDidLoad
14 {
15 [super viewDidLoad];
16
17 [self loadString:@"http://m.baidu.com"];
18 }
19
20 // 让浏览器加载指定的字符串,使用m.baidu.com进行搜索
21 - (void)loadString:(NSString *)str
22 {
23 // 1. URL 定位资源,需要资源的地址
24 NSString *urlStr = str;
25 if (![str hasPrefix:@"http://"]) {
26 urlStr = [NSString stringWithFormat:@"http://m.baidu.com/s?word=%@", str];
27 }
28
29 NSURL *url = [NSURL URLWithString:urlStr];
30
31 // 2. 把URL告诉给服务器,请求,从m.baidu.com请求数据
32 NSURLRequest *request = [NSURLRequest requestWithURL:url];
33
34 // 3. 发送请求给服务器
35 [self.webView loadRequest:request];
36 }
37
38 #pragma mark - 搜索栏代理
39 // 开始搜索
40 - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
41 {
42 NSLog(@"%@", searchBar.text);
43 [self loadString:searchBar.text];
44
45 [self.view endEditing:YES];
46 }
47
48 // 文本改变
49 - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
50 {
51 NSLog(@"searchText - %@", searchText);
52 }
53
54 #pragma mark - WebView代理方法
55 #pragma mark 完成加载,页面链表数据会更新
56 - (void)webViewDidFinishLoad:(UIWebView *)webView
57 {
58 // 根据webView当前的状态,来判断按钮的状态
59 self.backButton.enabled = webView.canGoBack;
60 self.forwarButton.enabled = webView.canGoForward;
61 }
62
63 @end