更改 WKWebview 框架高度后如何删除 WKScrollView 内的空白区域?
Posted
技术标签:
【中文标题】更改 WKWebview 框架高度后如何删除 WKScrollView 内的空白区域?【英文标题】:How to remove blank space inside WKScrollView after change WKWebview frame height? 【发布时间】:2021-12-30 11:27:24 【问题描述】:改变WKWebview的框架高度后如何去除空白区域? 我想在键盘出现时更改 webview 的高度,但是在框架高度更改后,html 正文下方有一个额外的空间。而这个额外的空白区域的高度大约是键盘的高度。
这里是sn-p的代码:
NotificationCenter.default.rx
.notification(UIApplication.keyboardDidShowNotification)
.subscribe(onNext: [weak self] keyboardConfig in
if let userInfo = keyboardConfig.userInfo
let keyboardBounds = (userInfo["UIKeyboardFrameEndUserInfoKey"] as! NSValue).cgRectValue;
self?.webView.snp.remakeConstraints( make in
make.left.right.top.equalToSuperview();
/// remake from screen height to below height.
make.height.equalTo(UIScreen.main.bounds.size.height - keyboardBounds.size.height);
);
);
【问题讨论】:
检查它被调用了多少次。 @ShreeramBhat 只有一次 【参考方案1】:最后我仍然不知道如何删除这个额外的空白区域,但我想出了一个解决方法。
由于WKScrollView
是UIScrollView
的子类,所以UIScrollView Delegate
也适用于WKScrollView
;
因此 contentOffset 可以在 UIScrollView scrollViewDidScroll
委托方法中强制重置。下面提供了代码 sn-p。
/// Change webview frame when keyboard appear.
NotificationCenter.default.rx
.notification(UIApplication.keyboardDidShowNotification)
.subscribe(onNext: [weak self] keyboardConfig in
if let userInfo = keyboardConfig.userInfo, let this = self
let keyboardBounds = (userInfo["UIKeyboardFrameEndUserInfoKey"] as! NSValue).cgRectValue;
this.webView.snp.remakeConstraints( make in
make.left.right.top.equalToSuperview();
/// remake from screen height to below height.
make.height.equalTo(UIScreen.main.bounds.size.height - keyboardBounds.size.height);
);
let originalOffset = this.webView.scrollView.contentOffset;
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2)
this.webView.scrollView.contentOffset = originalOffset;
);
/// Force reset contentOffset when the contentOffset is out of HTML Body
extension YourWebviewVC: UIScrollViewDelegate
internal func scrollViewDidScroll(_ scrollView: UIScrollView)
self.adjustWebviewOffsetFor(scrollView);
private func adjustWebviewOffsetFor(_ scrollView: UIScrollView, animated: Bool = false)
let currentY = scrollView.contentOffset.y + scrollView.frame.height;
if currentY > scrollView.contentSize.height
let maxOffset = scrollView.contentSize.height - scrollView.frame.height;
scrollView.setContentOffset(CGPoint(x: 0, y: maxOffset), animated: animated);
/// Don't forgot set webview scroolView's delegate, for example
self.webView.scrollView.delegate = self;
self.webView.scrollView.showsVerticalScrollIndicator = false;
【讨论】:
以上是关于更改 WKWebview 框架高度后如何删除 WKScrollView 内的空白区域?的主要内容,如果未能解决你的问题,请参考以下文章