单击“查看更多"按钮后,“文本视图"会展开或收缩 [英] Text View expand or contract upon clicking see more button

查看:71
本文介绍了单击“查看更多"按钮后,“文本视图"会展开或收缩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
}

这是屏幕截图

现在,我最初希望文本视图显示一些文本,然后单击查看更多"按钮,它应该展开,并且在扩展时,如果字符串的长度只有几行,则按钮文本也应该更改为较少显示,查看更多"按钮应该躲起来.我遇到的解决方案涉及 UILabel ,我不能使用它,因为这样单元格的高度就不会动态变化.另外,没有像 numberOfLines 这样的textView属性,因此我可以使用它.请为我指明正确的方向.

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.

推荐答案

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)

请尝试使用上述扩展方法,在其中输入textview的宽度和字体.此方法将动态设置您的textview的高度.还要使用自己的逻辑来计算看到更多和看到更少的按钮时将发生的情况.

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.

这篇关于单击“查看更多"按钮后,“文本视图"会展开或收缩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆