我已经努力解决这个问题两天了,所以现在我谦卑地向互联网上的智者们求助。
我正在展示一篇文章作为我的UITableView
的一部分。为了正确显示,我需要为单元格提供一个高度,我希望它与UIWebView
的高度相同,这样我就可以禁用WebView的滚动并将Web内容完整地显示为静态单元格。
我的第一个尝试是在heightForRowAtIndexpath
方法中进行呈现,但显然这行不通,因为我需要等待UIWebViewDelegate
告诉我WebView何时完全加载并具有高度。过了一会儿,我找到了一个可行的解决方案,它使用Web视图委托在Web视图加载完成时刷新单元格高度。
这很好,直到屏幕大小改变为止。要么是从旋转或全屏我的UISplitView
。我在didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation)
中强制更新了它,但这会导致它在达到正确高度之前闪烁大约10次。我记录了这个变化,似乎WebView调用自身多次,导致了循环。
如此日志所示,从我旋转屏幕开始。
它每次重新加载时都会闪烁一次,正如你所看到的,它会重新加载自己多次。
所以,我需要一种方法来在UITableView
中显示整个Web视图内容,并在屏幕大小改变时可靠地获取高度。如果有人以前已经成功解决这个问题,请告诉我。如果有人能解决这个问题,我将给予奖励并把我的长子送出去,因为这让我发疯了。
这里是我相关的代码。
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
switch indexPath.row {
case 4:
//Content
print("Height for row called")
return CGFloat(webViewHeight)
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch (indexPath.row){
//HTML Content View
case 4:
let cell = tableView.dequeueReusableCellWithIdentifier("ContentCell", forIndexPath: indexPath)
var contentCell = cell as? ContentCell
if contentCell == nil {
contentCell = ContentCell()
}
contentCell?.contentWebView.delegate = self
contentCell?.contentWebView.scrollView.userInteractionEnabled = false
contentCell?.contentWebView.loadHTMLString((post?.contentHTML)!, baseURL: nil)
print("Cell For row at indexpath called")
return contentCell!
}
func webViewDidFinishLoad(webView: UIWebView) {
updateHeight()
}
func updateHeight(){
let webView = (self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 4, inSection: 0)) as! ContentCell).contentWebView
if self.webViewHeight != Double(webView.scrollView.contentSize.height) {
print("Previous WV Height = \(self.webViewHeight), New WV Height = \(webView.scrollView.contentSize.height)")
self.webViewHeight = Double(webView.scrollView.contentSize.height)
tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 4, inSection: 0)], withRowAnimation: .Automatic)
} else {
return
}
}
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
print("rotated")
self.updateHeight()
//tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 4, inSection: 0)], withRowAnimation: .Automatic)
}
willDisplayCell
)。这样可以避免重新加载所有内容,如果单元格离开屏幕,也不需要等待webview显示。 - amadour