iOS导航栏上实现webView的网页返回及关闭按钮

QQ20160307-0@2xSimulator-Screen-Shot-2016年3月7日-下午2.56.23
1、功能描述:
1.1、webView中加载多层网页时需要实现浏览器的“返回”功能;
2.2、同时需要实现iOS自身的返回导航控制器的上一个页面;
2、应用场景
2.1、webView
3、实现原理:
3.1、通过webview的canGoback来判断是否能够返回,从而决定“关闭”按钮的隐藏与显示;
3.2、在webview的代理方法webViewDidStartLoad、webViewDidFinishLoad两个方法中判断;
3.3、修改导航栏的leftBarbuttonItems来增加或删除“关闭”按钮;
3.4、通过canGoback来修改返回按钮的事件;
4、部分代码
4.1、SAWebViewCtrl.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//
//? SAWebViewCtrl.m
//? Test
//
//? Created by 余西安 on 16/3/7.
//? Copyright ? 2016年 Sian. All rights reserved.
//
?
#import "SAWebViewCtrl.h"
#import "UIBarButtonItem+SA.h"
?
@interface SAWebViewCtrl () 
?
@property (nonatomic, strong) UIWebView *webView;
?
@property (nonatomic, strong) UIBarButtonItem *backItem;
?
@property (nonatomic, strong) UIBarButtonItem *closeItem;
?
@end
?
@implementation SAWebViewCtrl
?
- (void)viewDidLoad
{
????[super viewDidLoad];
????self.navigationItem.title = @"WebView";
????// 添加webView
????self.webView = [[UIWebView alloc] init];
????self.webView.delegate = self;
????self.webView.frame = self.view.bounds;
????self.webView.autoresizingMask = 255;
????[self.view addSubview: self.webView];
????// 初始化返回、关闭两个按钮
????self.backItem = [UIBarButtonItem backButtonWithTarget:self action:@selector(backEven:)];
????self.closeItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(popPage)];
????[self setLeftBarButton];
????// 加载网页
????NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
????[self.webView loadRequest:[NSURLRequest requestWithURL:url]];
}
?
#pragma mark - 网页代码方法
/// 网页开始加载时调用
- (void)webViewDidStartLoad:(UIWebView *)webView
{
????[self setLeftBarButton];
????[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
}
/// 网页加载完毕时调用
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
????[self setLeftBarButton];
????[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
?
#pragma mark - 事件响应
/// 返回按钮事件
- (void)backEven:(UIButton *)button
{
????if ([self.webView canGoBack]){
????????[self.webView goBack];
????}else{
????????[self popPage];
????}
}
/// 关闭事件
- (void)popPage
{
????[self.navigationController popViewControllerAnimated:YES];
}
/// 刷新左上角按钮
- (void)setLeftBarButton
{
????if ([self.webView canGoBack]){
????????[self.navigationItem setLeftBarButtonItems:@[self.backItem, self.closeItem]];
????}else{
????????[self.navigationItem setLeftBarButtonItems:@[self.backItem]];
????}
}
@end

5、源代码下载
Test

Leave a Reply