简体   繁体   中英

Adjust height of UITableViewCell to height of UITextView

I got two cells in my UITableView . One is a custom UITableViewCell and the other is a cell with a UITextView inside and called the type TextViewCell .

Because they are static I the cells are loaded in viewDidLoad method from a xib:

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:

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. In fact the cells gets smaller. The constraints of the TextViewCell look like this: 在此输入图像描述

Any suggestions?

I think you need to use self-sizing UITableViewCell . Replace your current implementation of heightForRowAt with the following:

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. 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.

You should get the height of UITextView in heightForRowAt and return this height as cell height. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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