在项目中,我们经常会需要加载网页,因此 UIWebView 或者 WKWebView 成为了不可或缺的开发控件。iOS8 之前使用的是 UIWebView,但是使用过的同学会发现 UIWebView 占用的内存较多,达到峰值时更是夸张。iOS8 之后,苹果推出了一种新的控件——WKWebView。据官方介绍,WKWebView 的性能优化比 UIWebView 提高了数倍,查看内存占用率确实比 UIWebView 降低了不少。虽然 WKWebView 也有不少缺点,但与 UIWebView 的高内存占用相比,开发者更愿意选择 WKWebView。因此,随着 iOS7 的淘汰,WKWebView 替代 UIWebView 成为了趋势。
开发中可能会有添加头部视图或尾部视图的需求,但我们不能像 UITableView 和 UICollectionView 那样方便地添加头部或尾部视图。
pod 'ZBWKWebView'
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;
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;