It is not clear whether all iOS versions have this bug, my current version is iOS 15.0.2. When the webView height is reduced by changing the frame height or changing the height constraint, an extra blank area appears at the bottom of the HTML body in the WebView. This extra blank area is not within the contentSize of the WKScrollView, but can be slid and displayed… At first, I thought about how to delete this area, but the technology was limited, so I didn’t delete it…

Finally, this is done by using the scrollViewDidScroll of UIScrollView to listen to whether the current contentOffset is outside its normal range and reset the current contentOffset when it is. It’s fixed, but it doesn’t bounce when sliding to the bottom… If someone has a better solution, please advise. The code is as follows:

/// Force a resetting of contentOffset to the bottom of the WebView when sliding beyond the bottom of the WebView's 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); }}}Copy the code

The contents of the webView sometimes move up (about 30% of the time, for unknown reasons). This can be done by setting contentOffset to where it was before the height change, as shown in the following example:

/// 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) {
            /// key point!! It's a bit of a problem without delay. You can step on the pit 😂
            this.webView.scrollView.contentOffset =originalOffset; }}});Copy the code
  • StackOverflow link