【问题标题】:Swift: how to adapt UITableViewCell height to a UITextView inside itSwift:如何使 UITableViewCell 高度适应其中的 UITextView
【发布时间】:2016-03-16 16:15:19
【问题描述】:

UITextView 高度调整到其内容,然后将充当容器的UITableViewCell 高度调整到与UITextView 相同的高度,哪种方法最简单?

【问题讨论】:

    标签: ios swift uitextview uitableview


    【解决方案1】:

    将你的 UITextView 行数设置为 0。 在包含 tableView 的控制器的 viewDidLoad 中使用:

     tableView.estimatedRowHeight = 55.0
     tableView.rowHeight = UITableViewAutomaticDimension
    

    【讨论】:

    • 如果您的文本很大,则estimatedRowHeight 可能必须使用大于 55 的数字。
    • 是的,这个值取决于你的 UITableViewCell 中有什么
    【解决方案2】:

    要计算文本视图的高度,我认为您需要知道文本的高度。因此,在您的 heightForRowAtIndexPath 委托方法上,计算文本高度并使用以下方法返回:

    func heightWithConstrainedWidth(width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: CGFloat.max)
    
        let boundingBox = self.boundingRectWithSize(constraintRect, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
    
        return boundingBox.height
    }
    

    您需要将 textview 约束、底部、顶部、前导和尾随设置为 0,以便它们调整到单元格的大小。 代码被from here.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-20
      • 1970-01-01
      • 2011-04-24
      • 1970-01-01
      • 2013-08-24
      • 2020-11-24
      相关资源
      最近更新 更多