How to auto size UITableViewCell with underlying WKWebKit, so it respects the content of the web view?

梦想与她 提交于 2019-12-04 16:08:00

The problem is you never give to your cells a height. Setting the frame by hand

self.frame = CGRect(x: tableCellFrame.minX, y: tableCellFrame.minY, width: tableCellFrame.width, height: tableCellFrame.height + h)

is bad. You should always use the dedicated delegate method or the estimated row height technique (Using Auto Layout in UITableView for dynamic cell layouts & variable row heights).

The problem is sticky : you need to wait for the webview to load to calculate its height. But you need its height when heightForCell is called so before the content of the webview is loaded.

I see 5 solutions :

  • You transform your tableview into a giant webview containing all the news. And you inject the meta data by hand into the html
  • You parse the html and extract the info you need. This is possible only if all the news html have the same structure. And this is pretty hard too (RegEx match open tags except XHTML self-contained tags).
  • You proceed as you did. But when completionHandler is called, you call a delegate (your viewcontroller for instance) that will reload the corresponding cell and giving it its right height just calculated. This solution is simple but before each loading, you need to give at your cell a wrong height. So, you could define a loading state in your cell but you will always have a little glitch when a cell is about to appear.
  • You load the content of all of your cells and calculate their corresponding height on a background thread before displaying the tableview. You could use an Operation for each of your cells that will wait for the html of the cell to load and evaluate the given javascript. When all the operations are done, you reload your tableview
  • Change your design : display only a list of news and load the news content inside a separate view controller when a cell is selected
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!