2016-03-16 41 views
-1

如何使用代碼動態更改uitextview內的uitableviewcell的高度而不使用自動佈局?我會有uitableviewcell和uitextview裏面。 uitableviewcell將根據uitextview中的文本進行更改。如何使用代碼動態更改uitextview內的uitableviewcell的高度而不使用自動佈局?

+0

答案已過時,不推薦使用,您可以將其轉換爲新版本嗎? –

+0

到目前爲止你做了什麼? – Lee

+0

直到sizeWithFont這是棄用,並沒有發現在swift –

回答

0

這是我使用的代碼(基於舊的答案),評論描述每個部分:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 

    //width can be customized based on your needs - i have a border of 10 around my textView on the sides 
    let width = tableView.frame.size.width - 20 

    if let textView = /* your cell's textView if initialized and presented*/ { 
    //if textView is available, use `sizeThatFits` to optimize size 
    let height = textView.sizeThatFits(CGSize(width:width, height: CGFloat.max)).height 
    return height //in my code I have a minimum threshold enforces via return (height > 65.0) ? height : 65.0 
    }else{ 
     //if it doesn't exist, use `textViewHeightForText` to simulate as if it did 
     return textViewHeightForText(/*text to display */, andWidth: width) 
    } 
} 


internal func textViewHeightForText(text: String?, andWidth width: CGFloat) -> CGFloat { 
    //in case you need to know height before cell has been presented (and textView not set up yet), can make one here 
    let calculationView = UITextView() 
    //IMPORTANT - have to specify the name/size of your font 
    let attributedText = NSAttributedString(string: (text != nil) ? text! : "", attributes: [NSFontAttributeName : UIFont(name: "Helvetica Neue", size: 16.0)!]) 
    calculationView.attributedText = attributedText 
    let height = calculationView.sizeThatFits(CGSize(width: width, height: CGFloat.max)).height 
    return height 
} 

沒有顯示出來,因爲它取決於你的模型,方法是:

  • 存儲指針到每個已經呈現的textView(最簡單的方法是製作一個[NSIndexPath : UITextView],在cellForRowAtIndexPath期間設置它並在if let部分訪問它)
  • 訪問您的模型以獲取文本t帽子將被顯示,如果textView未呈現。這是必要的,因爲它需要在顯示單元之前進行規劃。
+0

完美答案,謝謝 –

+0

我有問題,當我重新加載表和滾動等待數據獲取桌子高度和textview高度都搞亂了,但是在完成後重新加載都很好。這裏有什麼問題? –

+0

沒有圖片我不能確定,但​​它聽起來像高度可能會返回0沒有文字,它的基礎上的大小。 – sschale

0

以編程方式使用它。你需要接受autoResizingMask的幫助。您需要爲UItableViewCell的所有4邊定義autoResizingMask爲textview,然後需要檢查文本。您需要爲textview設置SizeToFit屬性。他們是一種方法「 sizeWithFont constrainedToSize:lineBreakMode」,可以返回CGSize的NSString,然後你需要通過方法heightForRowAtIndexpath將高度從這個大小傳遞給UITableviewCell。這將解決您的問題。

相關問題