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[Objective-C] 纯文本查看 复制代码 //
// SAWebViewCtrl.m
// Test
//
// Created by 余西安 on 16/3/7.
// Copyright © 2016年 Sian. All rights reserved.
//
#import "SAWebViewCtrl.h"
#import "UIBarButtonItem+SA.h"
@interface SAWebViewCtrl () <UIWebViewDelegate>
@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、源代码下载
|