单击“查看更多”按钮后,文本视图将展开或收缩

时间:2017-10-04 11:09:09

标签: swift3 uitextview ios11 swift4 xcode9

在我的tableView单元格中,我有一个textView,其字符串我通过JSON获取并动态更新单元格高度

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

这是一个截图

enter image description here

现在我最初希望文本视图显示一个小文本,点击查看更多按钮时,它应该展开,扩展后,如果字符串的长度只是几行,按钮文本应该更改为更少。看到更多按钮应隐藏。我遇到的解决方案涉及UILabel而且我无法使用它,因为这时单元格的高度不会变得动态。此外,text numberOfLines没有属性,所以我可以使用它。请指出我应该做的正确的方向。

1 个答案:

答案 0 :(得分: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的高度。还有你自己的逻辑来计算会发生什么,看到更多,看到更少的按钮。