2017-10-04 31 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的高度。也可以将自己的逻辑用于计算看到更多并看到更少的按钮会发生什么。