WKWebView添加自定义headerView和footerView

pod 'ZBWKWebView'

在文件中引入头文件:#import "ZBWKWebView.h"
创建headerView

UIImageView *headerView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 200)];
    headerView.backgroundColor = [UIColor redColor];
    UIGraphicsBeginImageContextWithOptions(headerView.bounds.size, NO, 0);
    [headerView drawRect:headerView.bounds];
    NSString *headerStr = @"I am headerView";
    [headerStr drawAtPoint:CGPointMake(10, headerView.bounds.size.height * 0.5 - 30) withAttributes:@{NSFontAttributeName :     [UIFont italicSystemFontOfSize:45], NSForegroundColorAttributeName : [UIColor whiteColor]}];
    UIImage *headerImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    headerView.image = headerImage;
    
    //是否设置自定义headerView的背景色与WKWebView一致
    _webView.isSameColorWithHeaderView = NO;
    //设置头部视图
    _webView.headerView = headerView;

创建footerView

UIImageView *footerView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 200)];
    footerView.backgroundColor = [UIColor yellowColor];
    UIGraphicsBeginImageContextWithOptions(footerView.bounds.size, NO, 0);
    [footerView drawRect:footerView.bounds];
    NSString *headerStr = @"I am footerView";
    [headerStr drawAtPoint:CGPointMake(20, footerView.bounds.size.height * 0.5 - 30) withAttributes:@{NSFontAttributeName :           [UIFont italicSystemFontOfSize:45], NSForegroundColorAttributeName : [UIColor redColor]}];
    UIImage *headerImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    footerView.image = headerImage;
    
    //是否设置自定义footerView的背景色与WKWebView一致
    _webView.isSameColorWithFooterView = NO;
    //设置尾部视图
    _webView.footerView = footerView;

在代理方法中设置HeaderView和FooterView

//页面开始加载时调用

- (void)webView:(WKWebView * _Nonnull)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
            [_webView setupHeaderViewForWebView:(ZBWKWebView *)webView];
}
//页面完成加载时调用
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
            [_webView setupFooterViewForWebView:(ZBWKWebView *)webView];
}

你可能感兴趣的:(WKWebView添加自定义headerView和footerView)