在我的tableView单元格中,我有一个textView,其字符串我通过JSON获取并动态更新单元格高度
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 {
return 255
}
return UITableViewAutomaticDimension
}
这是一个截图
现在我最初希望文本视图显示一个小文本,点击查看更多按钮时,它应该展开,扩展后,如果字符串的长度只是几行,按钮文本应该更改为更少。看到更多按钮应隐藏。我遇到的解决方案涉及UILabel
而且我无法使用它,因为这时单元格的高度不会变得动态。此外,text numberOfLines
没有属性,所以我可以使用它。请指出我应该做的正确的方向。
答案 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的高度。还有你自己的逻辑来计算会发生什么,看到更多,看到更少的按钮。