2016-06-17 26 views
0

我正在顯示用戶在表格視圖中寫入的一些降價。我顯示這些降價文本的方式是將降價轉換爲HTML,然後在UIWebview上顯示HTML。因爲,我可以使用一些很酷的CSS。如何創建一個動態改變其高度以適應其內容的表格視圖單元格?

經過一番研究,我發現我可以設置estimatedRowHeight某些東西,並將rowHeight設置爲UITableViewAutomaticDimension。我也發現瞭如何設置UIWebView的框架,以使其適應其內容here

所以我寫了這個代碼:

var results: [Entry] = [] 

override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    return 1 
} 

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return results.count 
} 

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("resultCell") 
    let webView = cell?.contentView.viewWithTag(1) as! UIWebView 
    let entry = results[indexPath.row] 
    webView.loadHTMLString(entry.htmlDescription, baseURL: nil) 
    webView.delegate = self 

    return cell! 
} 

override func viewDidAppear(animated: Bool) { 
    super.viewDidAppear(animated) 
    tableView.reloadData() 
} 

override func viewDidLoad() { 
    tableView.estimatedRowHeight = 400 
    tableView.rowHeight = UITableViewAutomaticDimension 
} 

func webViewDidFinishLoad(webView: UIWebView) { 
    let height = CGFloat(webView.stringByEvaluatingJavaScriptFromString("document.height")!.toFloat()!) 
    var frame = webView.frame 
    frame.size.height = height 
    webView.frame = frame 
    webView.scrollView.contentSize = frame.size 
    webView.scrollView.frame = frame 

    print(frame) 
} 

results數組只是我顯示的東西。正如你所看到的,我想在每個Web視圖中顯示結果的htmlDescription

而在webViewDidFinishLoad委託方法中,我只是做了前面提到的文章:評估一些JS並更新Web視圖的框架。

但是,這種行爲遠沒有我的預期。

  • 首先,表格視圖單元的高度是默認高度。
  • 當我嘗試滾動web視圖時,我不能。他們只是反彈回來。
  • 控制檯說:

警告只有一次:檢測到其中的約束隱約暗示的零的實現代碼如下單元格的內容視圖的高度的情況下。我們正在考慮無意的崩潰並使用標準高度。

我不知道什麼提示表視圖單元格的高度應爲0

  • 控制檯還打印的Web視圖的新框架。我只有3個視圖,但有6幀:

(0.0,0.0,320.0,315.0)

(0.0,0.0,320.0,363.0)

(0.0,0.0 ,320.0,216.0)

(0.0,0.0,320.0,315.0)

(0.0,0.0,320.0,363.0)

(0.0,0.0,320.0,216.0)

而且高度似乎是非常正確的,而不是默認的表格視圖單元格高度。

我知道我可以,如果我既可以解決這一問題:

  • 才知道的HTML被加載,或Web視圖的內容大小;
  • 當所有Web視圖完成加載時重新加載表視圖。 (因爲我可能會有很多網絡瀏覽量,所以我應該儘可能少地撥打reloadData,否則會很慢。)

我該怎麼做?

這不是How to make UITableViewCell adjust height to fit its content?的重複,因爲該問題的表視圖是靜態的。它的內容一旦加載就不會改變。但我的網頁視圖會加載HTML。

+0

你的tableView從數組中取? –

+0

你的意思是'結果'數組?是! @BashirSidani – Sweeper

+0

完美!並且所有單元格都具有相同的高度? –

回答

相關問題