【发布时间】:2017-09-06 23:32:05
【问题描述】:
我需要以编程方式将两种不同类型的单元格添加到我的 UITableView。这些单元格的内容直到运行时才知道。第一种是 HTML 格式的字符串,第二种是图像。这些单元格可以任意组合,并且可以以任意顺序出现。
在 IB 中,我设置了两个原型单元,一个 id 为“htmlCell”,另一个为“imageCell”。以下是相关代码:
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "htmlCell")
let thisSection = self.sections[indexPath.row]
if thisSection.type! == "html" {
let htmlString = thisSection.text
let htmlHeight = contentHeights[indexPath.row]
let webView:UIWebView = UIWebView(frame: CGRect(x:0, y:0, width:cell.frame.size.width, height:htmlHeight))
cell.addSubview(webView)
webView.tag = indexPath.row
webView.scrollView.isScrollEnabled = false
webView.isUserInteractionEnabled = false
webView.delegate = self
webView.loadHTMLString(htmlString!, baseURL: nil)
} else if thisSection.type! == "image" {
cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "imageCell")
let imageName = "logo"
let image = UIImage(named: imageName)
let imageView = UIImageView(image: image)
imageView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width-20, height: 200)
cell.addSubview(imageView)
return cell
}
return cell
}
func webViewDidFinishLoad(_ webView: UIWebView) {
if (contentHeights[webView.tag] != 0.0) {
// we already know height, no need to reload cell
return
}
let strHeight = webView.stringByEvaluatingJavaScript(from: "document.body.scrollHeight")
contentHeights[webView.tag] = CGFloat(Float(strHeight!)!)
tableView.reloadRows(at: [NSIndexPath(item: webView.tag, section: 0) as IndexPath], with: UITableViewRowAnimation.automatic)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return self.contentHeights[indexPath.row]
}
内容已加载,但有点混乱。这是提供示例的屏幕截图。在这种情况下,图像应该出现在两个 webview 之间。但正如您所见,图像直接落在第二个 webview 的顶部,两个顶部边框对齐。
此外,当我单击图像时,它会完全消失。我假设它落后于第二个 webview。只是猜测。
我正在使用的 CGRects 目前有一些任意的宽度和高度。我怀疑这就是部分问题所在。最后,无论 webview 内容的真实高度如何,webViewDidFinishLoad 总是返回 667.0 的高度。
有人知道我怎样才能让这些视图按正确的顺序出现吗?谢谢。
【问题讨论】:
标签: ios swift uitableview webview