Search code examples
swiftwkwebview

How to get WKWebview content size in swift?


i have a problem get the WKWebview real content size, any ideas?

How to determine the content size of a WKWebView? the answer above do NOT work for me, any ideas? Thanks!


Solution

  • The code below worked for me, but this maybe go wrong once WKWebview's view tree changes. post your best answer, thanks!

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            if let scroll_cls = NSClassFromString("WKChildScrollView"),
               let compose_cls = NSClassFromString("WKCompositingView") {
                let viewss = webView.allSubViewsOf(cls: scroll_cls)
                if let first = viewss.first?.subviews.first,
                   first.isKind(of: compose_cls) {
                    if webView.bounds.height >= first.bounds.height {
                        // webivew is at bottom
                    }
                }
            }
            
        }
    }
    
    
    extension UIView {
        func allSubViewsOf(cls: AnyClass) -> [UIView] {
            var all = [UIView]()
            func getSubview(view: UIView) {
                if view.isKind(of: cls) {
                    all.append(view)
                }
                guard view.subviews.count > 0 else { return }
                view.subviews.forEach{ getSubview(view: $0) }
            }
            getSubview(view: self)
            return all
        }
    }