Swift iOS : 如果Cell內部有webview怎麼自適應呢

RecoReco發表於2019-03-03

Cell高度自適應的問題真多。現在,如果內部有webView,內容動態裝入,大小也是各不相同的,並且高度必須根據內容,而不是view本身的高度來適應,怎麼辦呢?特別是如果有多個webView的情況下。
這樣就可以了:

  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,在此處獲得高度。

其次,多個webview會需要在一個事件內監聽,因此,必須區別它們,程式碼中採用了webview.tag屬性,賦值為此webview的cell的indexPath,把它記錄到高度陣列內。如果陣列內的高度有值了,那麼就不必在寫入了。

最後,tableView是可以區域性重新整理的,那個高度變了就重新裝入那個cell,做法就是使用reloadRows方法即可。

此案例的好處是簡單,可以用來說明問題,但是明視訊記憶體在著適應性問題,比如webview.tag記憶體儲的是indexPath.row,而不是indexPath,那麼在有多個section的TableView時,此程式碼就無法完成功能了。接下來的程式碼會更有通用性:

 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。

還有就是,webview高度一旦確定,就會重新裝入對應的cell,並重新整理此cell的高度,而webview的高度,使用了佈局技術,讓它可以跟隨cell高度而伴隨增大。這樣就不必自己計算檢視的frame了。

相關文章