2016-04-02 19 views
1

的高度我有一個UIViewController它具有以下層次結構(與他們NSLayoutConstraint S):獲得UIScrollView的內容查看

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之後獲得視圖約束的高度。

回答

0

當嘗試調整網頁視圖的大小以適應其內容時,難以解決的問題是網頁視圖本身並不知道其內部顯示DOM的內容有多高。你需要做的是向DOM詢問DOM的內容有多高,通過JavaScript。在我們的代碼,我們做這樣的事情:

[webView stringByEvaluatingJavaScriptFromString: @"document.height"] 

或斯威夫特:

webView.stringByEvaluatingJavaScriptFromString("document.height") 

,然後用這個值來選擇一個大小爲我們的UIWebView。

+0

謝謝,但我想得到的是'UIView-ContentView(UIScrollview的零邊距和UIScrollVIew的父母的等高度;代碼中提到的self.contentView的總高度)',基於該高度我會更新UIScrollView的高度ContentSize。 –