2017-10-04 33 views
2

在我的tableView細胞膨脹或收縮,我有一個TextView,其字符串我正在通過JSON獲取和動態更新單元格高度類似這樣的文本視圖在點擊看更多的按鈕

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 
    if indexPath.section == 0 { 
     return 255 
    } 
    return UITableViewAutomaticDimension 
} 

下面是截圖

enter image description here

現在開始,我想文本視圖來顯示一個小的文本以及在點擊看更多的按鈕,它應該擴大和膨脹時按鈕上的文字應該改變看也較少,如果字符串的長度僅有幾行,看應該隱藏更多的按鈕。我遇到的解決方案涉及UILabel,我不能使用它,因爲那麼單元格的高度將不會變爲動態。也沒有像numberOfLines textView的屬性,所以我可以使用它。請指出一個正確的方向,我該怎麼做。

回答

0
extension String { 

    func customHeight(constraintedWidth width: CGFloat, font: UIFont) -> CGFloat { 
    let label = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: .greatestFiniteMagnitude)) 
    label.numberOfLines = 0 
    label.text = self 
    label.font = font 
    label.sizeToFit() 

    return label.frame.height 
} 

} 

使用這個擴展,如下面的代碼,

let height = item.yourText.customHeight(constraintedWidth: cell.textView.bounds.width, font: UIFont.systemFont(ofSize: 17, weight: UIFontWeightSemibold)) 
cell.textViewHeightConstraint.constant = (height) 

請嘗試使用,你在你的TextView和字體的寬度通過上面的擴展方法。這個方法會動態地設置你的textview的高度。也可以將自己的邏輯用於計算看到更多並看到更少的按鈕會發生什麼。