iOS WKWebView简单实现
#import “ViewController.h” #import <WebKit/WebKit.h> @interface ViewController () @property (nonatomic,strong)WKWebView *webView; @end @implementation ViewController (void)viewDidLoad { [super viewDidLoad]; _webView = [[WKWebView alloc] initWithFrame:self.view.bounds];//初始化 [self.view addSubview:_webView]; //1.网络 _webView.allowsBackForwardNavigationGestures = YES; NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com/"]]; [_webView loadRequest:request]; //2.本地html //获取bundlePath 路径 NSString *bundlePath = [[NSBundle mainBundle] bundlePath]; //获取本地html目录 basePath NSString *basePath = [NSString stringWithFormat: @"%@/dist", bundlePath]; //获取本地html目录 baseUrl NSURL *baseUrl = [NSURL fileURLWithPath: basePath isDirectory: YES]; NSLog(@"%@", baseUrl); //html 路径 NSString *indexPath = [NSString stringWithFormat: @"%@/index.html", basePath]; //html 文件中内容 NSString *indexContent = [NSString stringWithContentsOfFile: indexPath encoding: NSUTF8StringEncoding error:nil]; //显示内容 [webview loadHTMLString: indexContent baseURL: baseUrl]; }
WKWebView实现背景透明
@interface 你的页面 ()<WKNavigationDelegate>
//遵循协议
_webView.navigationDelegate = self;
//关键一句 self.webView.opaque = NO; //或者 [self.webView setOpaque:NO]; // 似乎这两句没什么用 self.webView.backgroundColor = [UIColor clearColor]; self.webView.scrollView.backgroundColor = UIColor.clearColor;
亲测有效
如果你要实现网页文件显示,比如说这个
https://img.book118.com/sr1/M00/06/0A/wKh2AlywRP2IFAFzAAEuKOCu_hcAAcEngFumBwAAS5A024.png
那么可以这样实现
#import <UIKit/UIKit.h> #import <WebKit/WebKit.h> @interface ViewController : UIViewController @property (nonatomic, strong) WKWebView *webView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // 初始化WKWebView并添加到视图 WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init]; self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuration]; [self.view addSubview:self.webView]; // 创建包含<img>标签的HTML字符串 NSString *imageUrl = @"https://img.book118.com/sr1/M00/06/0A/wKh2AlywRP2IFAFzAAEuKOCu_hcAAcEngFumBwAAS5A024.png"; NSString *htmlString = [NSString stringWithFormat:@"<html><body><img src='%@' style='width:100%%;height:auto;'/></body></html>", imageUrl]; // 加载HTML字符串到WKWebView [self.webView loadHTMLString:htmlString baseURL:nil]; } @end