如何在更改WKWebview的帧高后删除空白区域?
当键盘出现时,我想要改变webview的高度,但是在帧高改变之后,HTML主体下面有一个额外的空间。这个额外空白区域的高度大约是键盘的高度。
下面是代码片段:
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);
});
}
});

发布于 2021-12-31 07:31:44
最后,我仍然不知道如何删除这个额外的空白区域,但我想出了一个解决办法。
因为WKScrollView是UIScrollView的子类,所以UIScrollView Delegate也适用于WKScrollView;
因此,contentOffset可以在UIScrollView scrollViewDidScroll委托方法中强制重新分配。下面提供了代码片段。
/// 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;https://stackoverflow.com/questions/70530990
复制相似问题