Text View expand or contract upon clicking see more button

旧时模样 提交于 2019-12-10 23:08:51

问题


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

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:


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.



来源:https://stackoverflow.com/questions/46563347/text-view-expand-or-contract-upon-clicking-see-more-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!