1.最简单的,只显示内容没有交互。
复制代码即可运行,可拖拽窗口。
#import "ViewController.h" #import <WebKit/WebKit.h> @interface ViewController () @property (nonatomic,strong)WKWebView * webView; @end @implementation ViewController -(void)viewDidLoad { [super viewDidLoad]; //观察窗口拉伸 [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(screenResize) name:NSWindowDidResizeNotification object:nil]; //初始化 _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)]; //加载出来 [self.view addSubview:_webView]; //1.网络 _webView.allowsBackForwardNavigationGestures = YES; NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://www.hao123.com/"]]; [_webView loadRequest:request]; } -(void)screenResize{ NSLog(@"观察窗口拉伸"); NSLog(@"%.2f===%.2f",self.view.bounds.size.width,self.view.bounds.size.height); _webView.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height); } - (void)setRepresentedObject:(id)representedObject { [super setRepresentedObject:representedObject]; // Update the view, if already loaded. } @end
最近在做项目的时候遇到一个奇怪的问题,WKWebView加载一些页面的时候会出现页面内无法跳转链接,但是有些网页是可以的,最后查阅了很多资料才找到最终解决办法。
此处感谢 dengjx_ios
2.可进行简单的交互增加代码如下
(1)引进代理
@interface ViewController ()<WKNavigationDelegate>
(2)增加代理引用的地方
//1.网络 self.webView.navigationDelegate = self;
(3)实现下面的代理方法
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler { if (navigationAction.targetFrame == nil) { [webView loadRequest:navigationAction.request]; } decisionHandler(WKNavigationActionPolicyAllow); }
运行之后,代码就可以实现简单的交互了。
3.增加前进后退页面
待续