UIWebView dynamic content size

后端 未结 9 1632
北海茫月
北海茫月 2020-12-01 09:21

I\'ve been looking around and wasnt able to see any swift related ways to do this. I\'m trying to get my UIWebViews height to be dynamic. I have a UIWebView that loads data

9条回答
  •  天命终不由人
    2020-12-01 09:57

    Here is my custom class to work with custom UIWebViews, it has everything in it to get the correct scrollview content height, set UIWebView height and create a custom height constraint to get autolayout working. It also loads some custom CSS styling...

    class CustomUIWebView: UIWebView, UIWebViewDelegate {
    
        required init(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            self.scrollView.scrollEnabled = false
            self.scrollView.bounces = false
            self.delegate = self
        }
    
        override init(frame: CGRect) {
            super.init(frame: frame)
            self.scrollView.scrollEnabled = false
            self.scrollView.bounces = false
            self.delegate = self
        }
    
        override func loadHTMLString(string: String!, baseURL: NSURL!) {
            var cssURL:String = NSBundle.mainBundle().pathForResource("webview", ofType: "css")!
            var s:String = ""+string+"";
            var url:NSURL
    
            if baseURL == nil {
                url = NSBundle.mainBundle().bundleURL
            } else {
                url = baseURL
            }
    
            super.loadHTMLString(s, baseURL: url)
        }
    
        func webViewDidFinishLoad(webView: UIWebView) {
            self.webViewResizeToContent(webView)
        }
    
        func webViewResizeToContent(webView: UIWebView) {
            webView.layoutSubviews()
    
            // Set to smallest rect value
            var frame:CGRect = webView.frame
            frame.size.height = 1.0
            webView.frame = frame
    
            var height:CGFloat = webView.scrollView.contentSize.height
            println("UIWebView.height: \(height)")
    
            webView.setHeight(height: height)
            let heightConstraint = NSLayoutConstraint(item: webView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.Height, multiplier: 1.0, constant: height)
            webView.addConstraint(heightConstraint)
    
            // Set layout flag
            webView.window?.setNeedsUpdateConstraints()
            webView.window?.setNeedsLayout()
        }
    
    }
    

提交回复
热议问题