【问题标题】:Text View expand or contract upon clicking see more button单击查看更多按钮时文本视图展开或收缩
【发布时间】:2017-10-04 11:09:09
【问题描述】:

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

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

这是截图

现在,最初我希望文本视图显示一些文本,单击查看更多按钮时,它应该展开,并且在展开时,如果字符串的长度只是几行,则按钮文本也应该更改为查看更少,查看更多按钮应该隐藏。我遇到的解决方案涉及UILabel,我不能使用它,因为这样单元格的高度就不会变成动态的。也没有像 numberOfLines 这样的 textView 属性,所以我可以使用它。请指出我应该做的正确方向。

【问题讨论】:

    标签: swift3 uitextview ios11 swift4 xcode9


    【解决方案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
    }
    
    }
    

    像下面的代码一样使用这个扩展,

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

    请尝试使用上述扩展方法,您可以在其中传递文本视图的宽度和字体。此方法将动态设置文本视图的高度。还可以使用您自己的逻辑来计算“查看更多”和“查看更少”按钮会发生什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多