2016-07-14 43 views
0

我有WKWebView在一個單元格內,但問題是當旋轉手機時,我得到WkWebView滾動高度的舊值,因此,完全加載。WKWebView在旋轉手機後得到舊值滾動高度iOS9

override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { 
    self.contentHeights[3] = self.webView.scrollView.contentSize.height 
} 

這種方法改變表格單元格的行,但我得到的值是在之前進行旋轉的高度。

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat 
{ 
    if indexPath.row == 3{ 
     return contentHeights[indexPath.row] 
    }else{ 
     contentHeights[indexPath.row] = UITableViewAutomaticDimension 
     return contentHeights[indexPath.row] 
    } 


} 
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
    if indexPath.row == 3{ 
     return contentHeights[indexPath.row] 
    }else{ 
     return UITableViewAutomaticDimension 
    } 
} 

行3是WkWebView任何幫助?

回答

0

我讀了幾篇文章後,我創建了兩種方式來解決問題。

首先我用志願

addObserver(self, forKeyPath: "webView.scrollView.contentSize", options: .New, context: nil) 

override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { 
if keyPath == "webView.scrollView.contentSize" { 
    if let nsSize = change[NSKeyValueChangeNewKey] as? NSValue { 
     let height = nsSize.CGSizeValue().height 
     // Do something here using content height. 
    } 
}} 

removeObserver(self, forKeyPath: "webView.scrollView.contentSize", context: nil) 

第二種方法是JavaScript的一個事件:

添加以下代碼的html代碼:

<script>$(document).ready(function(){$(document).resize(function() {webkit.messageHandlers.callbackHandler.postMessage($(document).height())});});</script> 

添加WkWebView以下配置:

var contentController:WKUserContentController! 
override func loadView() { 
    super.loadView() 
    contentController = WKUserContentController() 
    contentController.addScriptMessageHandler(
     self, 
     name: "callbackHandler" 
    ) 

    config = WKWebViewConfiguration() 
    config.userContentController = contentController 
    self.webView = WKWebView(frame: CGRectMake(0, 0, self.view.frame.width, self.view.frame.height), configuration: config) 
} 

添加以下功能:

func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { 
    if(message.name == "callbackHandler") { 
     if !positionOrientationLanscape{ 
      sizeLanscape = CGFloat((message.body as! NSNumber).doubleValue) 
      contentHeights[4] = sizeLanscape 
     }else{ 
      sizePortrait = CGFloat((message.body as! NSNumber).doubleValue) 
      contentHeights[4] = sizePortrait 
     } 
    }  
} 

不要忘記DEINIT

deinit { 

     self.contentController.removeScriptMessageHandlerForName("callbackHandler") 
    }