Text View expand or contract upon clicking see mor

2019-07-13 11:11发布

In my tableView cell, I have a textView whose string i'm getting via JSON and updating the cell height dynamically like this

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

Here's a screenshot

enter image description here

Now initially i want text view to show a little text and upon clicking see more button it should expand and upon expansion the button text should change to see less also if the string's length is just a couple of lines, the see more button should hide. The solution's i've came across involve UILabel and i can't use it because then the cell's height won't become dynamic. Also there's no property of textView like numberOfLines so i can work with it. Please point me in a right direction what should i do.

1条回答
Luminary・发光体
2楼-- · 2019-07-13 11:48
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
}

}

Use this extension like the below code,

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

Please try using the above extension method where you pass in the width of your textview and the font. This method will dynamically set the height of your textview. Also put your own logic for calculating what will happen on see more and see less buttons.

查看更多
登录 后发表回答