Cell高度自適應的問題真多。如今,若是內部有webView,內容動態裝入,大小也是各不相同的,而且高度必須根據內容,而不是view自己的高度來適應,怎麼辦呢?特別是若是有多個webView的狀況下。
這樣就能夠了:html
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
window?.rootViewController = TableViewController()
return true
}
}
class Cell:UITableViewCell{
var webView = UIWebView()
override func layoutSubviews() {
self.contentView.addSubview(webView)
}
}
class TableViewController: UITableViewController, UIWebViewDelegate {
fileprivate let reuserId = "BookTableViewCellIdentifier"
override func viewDidLoad() {
self.tableView.register(Cell.self, forCellReuseIdentifier: reuserId)
}
var content : [String] = ["test1<br>test1<br>test1<br>test1<br>", "test22<br>test22<br>test22<br>test22<br>test22<br>test22"]
var contentHeights : [CGFloat] = [0.0, 0.0]
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return content.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuserId, for: indexPath) as! Cell
let htmlString = content[indexPath.row]
var htmlHeight = contentHeights[indexPath.row]
if htmlHeight == 0.0{
htmlHeight = 100
}
cell.webView.tag = indexPath.row
cell.webView.delegate = self
cell.webView.loadHTMLString(htmlString, baseURL: nil)
cell.webView.frame = CGRect(x:10, y:0, width:cell.frame.size.width, height:htmlHeight)
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
return contentHeights[indexPath.row]
}
func webViewDidFinishLoad(_ webView: UIWebView)
{
if (contentHeights[webView.tag] != 0.0)
{
// we already know height, no need to reload cell
return
}
contentHeights[webView.tag] = webView.scrollView.contentSize.height
print(contentHeights)
tableView.reloadRows(at: [IndexPath(row: webView.tag, section:0)], with: .automatic)
}
}複製代碼
首先webview只有裝入內容完成,才知道內容的高度的,所以須要經過委託,監聽事件webViewDidFinishLoad,在此處得到高度。web
其次,多個webview會須要在一個事件內監聽,所以,必須區別它們,代碼中採用了webview.tag屬性,賦值爲此webview的cell的indexPath,把它記錄到高度數組內。若是數組內的高度有值了,那麼就沒必要在寫入了。swift
最後,tableView是能夠局部刷新的,那個高度變了就從新裝入那個cell,作法就是使用reloadRows方法便可。數組
此案例的好處是簡單,能夠用來講明問題,可是明顯存在着適應性問題,好比webview.tag內存儲的是indexPath.row,而不是indexPath,那麼在有多個section的TableView時,此代碼就沒法完成功能了。接下來的代碼會更有通用性:bash
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
window?.rootViewController = TableViewController()
return true
}
}
class Cell:UITableViewCell{
var title = UILabel()
var webView = TJWeb()
override func layoutSubviews() {
self.contentView.addSubview(webView)
self.contentView.addSubview(title)
// layout code
let view2 = webView
let view1 = title
let view = self.contentView
view2.translatesAutoresizingMaskIntoConstraints = false
view1.translatesAutoresizingMaskIntoConstraints = false
let views = ["view1":view1,"view2":view2]
let hConstraint1=NSLayoutConstraint.constraints(withVisualFormat: "H:|-[view1]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
view.addConstraints(hConstraint1)
let hConstraint2=NSLayoutConstraint.constraints(withVisualFormat: "H:|-[view2]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
view.addConstraints(hConstraint2)
let vConstraint1=NSLayoutConstraint.constraints(withVisualFormat: "V:|-5-[view1]-5-[view2]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
view.addConstraints(vConstraint1)
}
}
class TJWeb : UIWebView,UIWebViewDelegate{
var indexPath : IndexPath!
override func layoutSubviews() {
isUserInteractionEnabled = false
}
}
class Item {
init(_ title : String?,_ content : String?){
self.title = title
self.content = content
}
var title : String?
var content : String?
}
var data = [
Item("1","test1<br>test1<br>test1<br>test1<br>"),
Item("2","test22<br>test22<br>test22<br>test22<br>test22<br>test22"),
Item("3","test22<br>test22<br>test22<br>test22<br>test22<br>test22"),
Item("4","test22<br>test22<br>test22<br>test22<br>test22<br>test22"),
Item("5","test22<br>test22<br>test22<br>test22<br>test22<br>test22"),
Item("6","test22<br>test22<br>test22<br>test22<br>test22<br>test22"),
]
class TableViewController: UITableViewController, UIWebViewDelegate
{
fileprivate let reuserId = "BookTableViewCellIdentifier"
override func viewDidLoad() {
self.tableView.register(Cell.self, forCellReuseIdentifier: reuserId)
}
var contentHeights : [IndexPath:CGFloat] = [:]
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuserId, for: indexPath) as! Cell
let htmlString = data[indexPath.row].content
var htmlHeight = contentHeights[indexPath]
if htmlHeight == nil{
htmlHeight = 100
}
cell.webView.indexPath = indexPath
cell.webView.delegate = self
cell.webView.loadHTMLString(htmlString!, baseURL: nil)
cell.title.text = data[indexPath.row].title
cell.title.backgroundColor = .blue
// layout section
// cell.webView.frame = CGRect(x:0.0, y:webTop, width:cell.frame.size.width, height:htmlHeight!)
// cell.title.frame = CGRect(x:0.0, y: 5.0 , width:cell.frame.size.width, height:titleHeight)
return cell
}
let fixWidth : CGFloat = 30
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
if contentHeights[indexPath] != nil {
return contentHeights[indexPath]! + fixWidth
}
return 44
}
func webViewDidFinishLoad(_ webView: UIWebView)
{
let web = webView as! TJWeb
if (contentHeights[web.indexPath] != nil)
{
// we already know height, no need to reload cell
return
}
contentHeights[web.indexPath] = webView.scrollView.contentSize.height
print(contentHeights)
tableView.reloadRows(at: [web.indexPath], with: .automatic)
}
}複製代碼
要點在於,傳入cell的webview是子類化的了,新的類內有一個屬性,能夠用來存在此webview所在的cell的indexPath。app
還有就是,webview高度一旦肯定,就會從新裝入對應的cell,並刷新此cell的高度,而webview的高度,使用了佈局技術,讓它能夠跟隨cell高度而伴隨增大。這樣就沒必要本身計算視圖的frame了。ide