获取UIScrollView contentView的高度

时间:2016-04-02 01:11:25

标签: ios swift uiscrollview uiwebview

我有一个UIViewController,它具有以下层次结构(带有NSLayoutConstraint s):

UIView
-UIScrollView
--UIView-ContentView (zero margins to the UIScrollview and equal height to UIScrollVIew's parent; mentioned in the code as self.contentView)
---UIView (fixed height, 0 top margin to Content View)
---UIView (fixed height, 0 top margin to above view)
---UIView (fixed height, 0 top margin to above view)
---UIView (fixed height, 0 top margin to above view)
---UIWebView (fixed height & linked to IBOutlet in the class; gets expanded)
---UILabel (top margin to UIWebView)
---UIView (fixed height, top margin to above label)
---UIView (fixed height, 0 top margin to above view)
---UIView (fixed height, 0 top margin to above view)
---UIView (fixed height, 0 top margin to above view)
---UIButton (fixed height, top margin to above view)

Scenario:
1. On viewDidLoad() I'm adding the HTML text by appending the JavaScript code that returns the height of the UIWebView
2. on UIWebViewDelegate method (shouldStartLoadWithRequest) I'm setting the following things:
- webViewHeight.constant (NSLayoutConstraint, linked from IB)
- self.scrollView.contentSize = CGSizeMake(self.view.frame.width, CGRectGetHeight(self.contentView.frame))


override func viewDidLoad() {
    self.webView.scrollView.scrollEnabled = false

    let heightHackScript = "<script type='text/javascript'>window.onload = function() { window.location.href = 'ready://' + document.body.offsetHeight; }</script>"

        if let cBody:NSData = self.model?.text_content {

          self.webView.loadHTMLString(heightHackScript + String(data: cBody, encoding: NSUTF8StringEncoding)!, baseURL: nil)
        }
  }


func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {

  let url = request.URL

  if navigationType == .Other {
    if url?.scheme == "ready" {
      webViewHeight.constant = (url?.host?.floatValue)!
      self.scrollView.contentSize = CGSizeMake(self.view.frame.width, CGRectGetHeight(self.contentView.frame))
      return false
    }
  }
  return true
}

问题是CGRectGetHeight(self.contentView.frame)无法获得所需的高度。有什么想法吗?

所以我想在HTML加载到UIWebView之后获得视图约束的高度。

1 个答案:

答案 0 :(得分:0)

尝试调整Web视图大小以适应其内容时的难题是,Web视图本身并不知道在其中显示的DOM内容可能有多高。你要做的就是通过JavaScript询问DOM的内容有多高。在我们的代码中,我们这样做:

[webView stringByEvaluatingJavaScriptFromString: @"document.height"]

或在Swift中:

webView.stringByEvaluatingJavaScriptFromString("document.height")

并使用结果值为UIWebView选择大小。