简体   繁体   English

将UITableViewCell的高度调整为UITextView的高度

[英]Adjust height of UITableViewCell to height of UITextView

I got two cells in my UITableView . 我的UITableView有两个单元格。 One is a custom UITableViewCell and the other is a cell with a UITextView inside and called the type TextViewCell . 一个是自定义UITableViewCell ,另一个是内部带有UITextView的单元格,称为TextViewCell类型。

Because they are static I the cells are loaded in viewDidLoad method from a xib: 因为它们是静态的,所以单元格从xib加载到viewDidLoad方法中:

textCell = Bundle.main.loadNibNamed(String(describing: TextViewCell.self),
                                        owner: self, options: nil)?.first! as! TextViewCell
ratingCell = Bundle.main.loadNibNamed(String(describing: RatingCell.self),
                                          owner: self, options: nil)?.first! as! RatingCell

Now I try to change the height with the the heightForRowAt delegate: 现在我尝试使用heightForRowAt委托更改高度:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if indexPath.section == 1 {
        return textCell.textView.contentSize.height
    }
    return ratingCell.ratingView.frame.height
}

I disabled scrolling on the UITextView but the cell is not resizing properly. 我禁用了UITextView上的滚动,但单元格没有正确调整大小。 In fact the cells gets smaller. 事实上,细胞变小了。 The constraints of the TextViewCell look like this: TextViewCell的约束如下所示: 在此输入图像描述

Any suggestions? 有什么建议?

I think you need to use self-sizing UITableViewCell . 我认为你需要使用自我调整大小的UITableViewCell Replace your current implementation of heightForRowAt with the following: 用以下内容替换当前的heightForRowAt实现:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    return UITableViewAutomaticDimension
}

Now height of cells in your UITableView object will be calculated automatically based on constraints. 现在,将根据约束自动计算UITableView对象中单元格的高度。 Also, add some estimated value for row height: 另外,为行高添加一些估计值:

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {

    return 100.0 // You can set any other value, it's up to you
}

Now you will see that the UITextView view fills the whole UITableViewCell cell. 现在您将看到UITextView视图填充整个UITableViewCell单元格。

You should get the height of UITextView in heightForRowAt and return this height as cell height. 您应该在heightForRowAt中获取UITextView的高度,并将此高度作为单元格高度返回。 See example below 见下面的例子

        let lblDescLong = UITextView()
        lblDescLong.textAlignment = .left
        lblDescLong.text = “your text for text view”
        lblDescLong.font = YourFont(size: 12)
        let newSize = lblDescLong.sizeThatFits(CGSize(width: widthForTextView, height: CGFloat.greatestFiniteMagnitude))
        return newSize.height

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM