首先创建一个webView对象和
private var webviewheight:CGFloat? =
private var webViewcell : UIWebView?
在viewDidLoad里面设置创建webViewcell,设置属性并用kvo监听webViewcell中scrollView的size的变化
self.webViewcell = UIWebView(frame: CGRectMake(16, 0, UIScreen.mainScreen().bounds.size.width - 32, 1))
self.webViewcell?.delegate = self
self.webViewcell?.userInteractionEnabled = false
self.webViewcell?.scalesPageToFit = true
self.webViewcell?.scrollView.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.New, context: nil)
在tableview的数据源中把webViewCell添加到cell上面
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableview.dequeueReusableCellWithIdentifier("FindDetailHuoDongNeiRongTableViewCell") as? FindDetailHuoDongNeiRongTableViewCell
cell?.selectionStyle = UITableViewCellSelectionStyle.None
if self.webViewcell != nil{
cell?.contentView.addSubview(self.webViewcell!)
}
return cell!
}
把监听到的高纪录一下,设置webviewcell的frame
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if keyPath == "contentSize"{ if self.webviewheight != object!.contentSize.height{
self.webviewheight = object!.contentSize.height
self.webViewcell?.frame = CGRectMake(16, 40, UIScreen.mainScreen().bounds.size.width - 32, webviewheight!)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableview.reloadData()
})
}
} }
移除监听
deinit{
webViewcell?.scrollView.removeObserver(self, forKeyPath: "contentSize")
}