2017-08-07 70 views
1

是否可以在將文本設置爲它之後調整UITabeView標題的大小? 在我的xib中,我得到了一個帶有高度爲42的標題的TableView,用於1行文本。對於2行我需要52的高度和3我需要62.標題動態設置到標題。但是在生命週期設置標題文本之前調用heightForHeaderInSection func。所以也許沒有顯示第2行& 3。在沒有自動佈局的情況下調整UITableView標題的大小

我寫了一個方法告訴我頭文件有多少行文本,但是如何更新頭文件?如果我打電話給tableView.reloadData(),我最終會處於一個無限循環。如果我爲每個lineamoun設置var t我發現heightForheaderInSection從未被調用過。

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { 

    let cell = tableView.dequeueReusableCell(withIdentifier: headerCell) as! SectionHeader 
    cell.titleLabel.text = self.sectionTitle 

    linesOfHeader = cell.getNumberOfLines() 


    return cell 
    } 



func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { 
     if(linesOfHeader == 1) { return 44} 
     else if(linesOfHeader == 2) {return 52} 
     else { return 62} 
    } 
+0

設置爲'linesOfHeader'屬性觀察者和調用'tableView.reloadData()'從內部'disSet ''lineOfHeader'的方法。這樣''tableView'每次'linesOfHeader'改變時只會重繪一次。 –

+0

有限的字符串方法可以幫助您獲得標籤的高度和寬度,您可以將高度傳遞給標題。 –

+0

@DávidPásztor同樣的循環。 reloadData()調用viewForHeaderInSection,其中我設置Header的行。所以我會以循環結束。 – elpatricko

回答

0

更好的解決方案,以支持動態頭高度是使用 「UITableViewAutomaticDimension」 是這樣的:

在viewDidLoad中添加這些行:

self.tableView.sectionHeaderHeight = UITableViewAutomaticDimension 
self.tableView.estimatedSectionHeaderHeight = 50 

並刪除功能heightForHeaderInSection

然後允許標籤擴展到所需的行數

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { 

    let cell = tableView.dequeueReusableCell(withIdentifier: headerCell) as! SectionHeader 
     cell.titleLabel.text = self.sectionTitle 
     cell.titleLabel.numberOfLines = 3 
    return cell 
    } 

如果標題高度重疊細胞高度以及添加這兩行viewDidLoad中

self.tableView.rowHeight = UITableViewAutomaticDimension 
    self.tableView.estimatedRowHeight = 40 // estimated cell height 
+0

'numberOfLines'參數應該設置爲0,所以'Autolayout'可以自己計算出必要的行數。另外,請記住'UITableViewAutomaticDimension'需要使用'Autolayout'。 –

相關問題