如何修复WebView调整大小时滚动卡顿的问题?
流畅实现浏览器工具栏滚动隐藏/显示的秘诀
所有网页浏览器底部都带有某种工具栏。向下滚动时工具栏会隐藏,页面高度随之增加。这一效果在Safari和Chrome中表现流畅,但在我测试过的其他浏览器(Microsoft Edge、Opera、DuckDuckGo、Mozilla Firefox、Brave)中都十分卡顿,原因是WebView会被重新调整大小并渲染。
我目前的实现代码如下:
WebView初始化代码(Objective-C)
self.webView = [[WKWebView alloc] init]; self.webView.scrollView.delegate = self; self.webView.frame = CGRectMake(0.0, 0.0, self.view.frame.size.width, self.view.frame.size.height); [self.view addSubview:self.webView]; [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.apple.com/iphone-14-pro/"]]];
滚动时调整WebView大小的代码(Objective-C)
- (void)scrollViewDidScroll:(UIScrollView *)scrollView { // 使用全局变量previousContentOffset if (scrollView.contentOffset.y > 0.0) { CGFloat movement = scrollView.contentOffset.y - self.previousContetOffset.y; CGFloat allowableMovement = 10.0; // 向下滚动 if (movement >= allowableMovement) { [UIView animateWithDuration:0.2 animations:^{ self.webView.frame = CGRectMake(0.0, 0.0, self.view.frame.size.width, self.view.frame.size.height); }]; self.previousContetOffset = scrollView.contentOffset; } // 向上滚动 if (movement <= -allowableMovement) { [UIView animateWithDuration:0.2 animations:^{ self.webView.frame = CGRectMake(0.0, 0.0, self.view.frame.size.width, self.view.frame.size.height - 80.0); // 工具栏高度 }]; self.previousContetOffset = scrollView.contentOffset; } } }
补充说明
- 我也可以用Swift实现该功能。
- 我有一个实现思路猜想:向下滚动时,先不把触摸事件传递给scrollView,页面实际不滚动,而是用触摸操作调整工具栏的垂直显示位置;当工具栏完全显示(对应滚动约50px的距离)后,再将触摸事件传递给下方的scrollView,页面才开始真正滚动。
想请教Safari和Chrome实现这一流畅效果的秘诀是什么?
内容的提问来源于stack exchange,提问作者Vulkan
相关产品推荐
相关产品推荐

